Closed
Description
Description
The Quantity
class in the healthchain/models/data/concept.py
file currently allows both string and float values for the value
field. We need to implement validation for conversions between string and float representations to ensure data consistency and prevent potential errors.
Context
This validation is important for maintaining data integrity within the Quantity
class, which is used in various concepts such as medication dosages and ranges. Proper validation will help prevent issues related to data type mismatches and ensure that all quantity values are consistently represented and can be reliably used in calculations or comparisons.
Possible Implementation
- Add a custom validator to the
Quantity
class using Pydantic's@validator
decorator. - Implement logic to convert string inputs to float when possible.
- Raise a
ValueError
with a descriptive message if the conversion fails. - Ensure that float values are properly formatted when converted to strings.
# healthchain/models/data/concept.py
class Quantity(DataType):
value: Optional[Union[str, float]] = None
unit: Optional[str] = None
@validator('value')
def validate_value(cls, v):
if isinstance(v, str):
try:
return float(v)
except ValueError:
raise ValueError(f"Invalid value for Quantity: '{v}'. Must be a valid number.")
return v
def str(self):
if self.value is not None:
return f"{self.value:.2f} {self.unit or ''}"
return ""
Possible Alternatives
- Restrict the
value
field to accept only float inputs, removing the string option entirely. - Implement a custom data type that handles both string and float representations internally while exposing a consistent interface.
- Use a third-party library specialized in handling quantities and units, such as
pint
, which could provide more robust unit conversion and representation capabilities.
Metadata
Metadata
Assignees
Labels
Type
Projects
Status
Done