Skip to content

Implement Validation for String-Float Conversions in Quantity Class #68

Closed
@jenniferjiangkells

Description

@jenniferjiangkells

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

  1. Add a custom validator to the Quantity class using Pydantic's @validator decorator.
  2. Implement logic to convert string inputs to float when possible.
  3. Raise a ValueError with a descriptive message if the conversion fails.
  4. 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

  1. Restrict the value field to accept only float inputs, removing the string option entirely.
  2. Implement a custom data type that handles both string and float representations internally while exposing a consistent interface.
  3. 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

No one assigned

    Labels

    Component: Interop EngineIssue/PR that relate to the interop engine component (CDA/HL7v2/FHIR)good first issueGood for newcomershacktoberfestIssues suitable for hacktoberfest

    Type

    No type

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions