feat: FromPyFromStr and ToStrToPy macros YAY

This commit is contained in:
J / Jacob Babich
2026-07-09 01:35:49 -04:00
parent c637ad2d76
commit 9a9cefee37
25 changed files with 343 additions and 394 deletions

View File

@@ -1,10 +1,6 @@
use std::str::FromStr;
use pyo3::{
exceptions::{PyException, PyValueError},
prelude::*,
};
use snafu::{ResultExt, Snafu};
use python_utils::{FromPyFromStr, ToStrToPy};
use strum::EnumString;
use uom::{
si::{
@@ -18,7 +14,7 @@ use uom::{
};
/// Power units
#[derive(Debug, Clone, Copy, EnumString, strum::Display)]
#[derive(Debug, Clone, Copy, EnumString, strum::Display, FromPyFromStr, ToStrToPy)]
#[strum(serialize_all = "snake_case")]
pub enum UnitOfMeasurement {
#[strum(serialize = "mW")]
@@ -37,42 +33,6 @@ pub enum UnitOfMeasurement {
BtuPerhour,
}
#[derive(Debug, Snafu)]
pub enum ExtractUnitOfMeasurementError {
/// couldn't extract the object as a string
ExtractStringError { source: PyErr },
/// couldn't parse the string as a [`UnitOfMeasurement`]
ParseError {
source: <UnitOfMeasurement as FromStr>::Err,
},
}
impl From<ExtractUnitOfMeasurementError> for PyErr {
fn from(error: ExtractUnitOfMeasurementError) -> Self {
match &error {
ExtractUnitOfMeasurementError::ExtractStringError { .. } => {
PyException::new_err(error.to_string())
}
ExtractUnitOfMeasurementError::ParseError { .. } => {
PyValueError::new_err(error.to_string())
}
}
}
}
// TODO: replace with a derive(PyFromStr) (analogous to serde_with::DeserializeFromStr) once I make one
impl<'a, 'py> FromPyObject<'a, 'py> for UnitOfMeasurement {
type Error = ExtractUnitOfMeasurementError;
fn extract(obj: Borrowed<'a, 'py, PyAny>) -> Result<Self, Self::Error> {
let s = obj.extract().context(ExtractStringSnafu)?;
let unit_of_measurement = UnitOfMeasurement::from_str(s).context(ParseSnafu)?;
Ok(unit_of_measurement)
}
}
impl UnitOfMeasurement {
pub fn into_uom<V>(&self, amount: V) -> Power<V>
where