You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I think it would be valuable to define the Quantity class as a pydantic model:
no need to perform the validation of input parameters
simplifies the development of API in sight of the current developments in the direction of WebApp
serialize and desirialize the model via json
The shortcut to that would be to define a __get_pydantic_core_schema__ method directly within the Quantity.
I did a proof of concept wrapping the Quantity object into a wrapper:
classQuantityWrapper(Quantity):
"""A wrapper for Quantity that allows for pydantic representation."""def__init__(self, value: list[float], units: str, **kwargs):
"""Initialize the QuantityWrapper."""super().__init__(value=value, units=units)
self.extra_fields=kwargs@classmethoddef__get_pydantic_core_schema__(cls, source_type, handler):
"""Define the pydantic core schema for QuantityWrapper."""defvalidate_quantity_type(obj):
ifisinstance(obj, cls):
returnobjifisinstance(obj, Quantity):
returncls(value=obj.value, b=obj.units)
raiseTypeError("Expected Quantity or QuantityWrapper instance.")
defserialize(instance):
base= {"value": instance.value, "units": instance.units.name}
return {**base, **instance.extra_fields}
returncore_schema.no_info_plain_validator_function(
validate_quantity_type,
json_schema_input_schema=core_schema.model_fields_schema(
{
"value": core_schema.list_schema(items_schema=core_schema.float_schema()),
"units": core_schema.str_schema(),
},
extras_schema=core_schema.any_schema(),
),
serialization=core_schema.plain_serializer_function_ser_schema(
serialize, return_schema=core_schema.dict_schema()
),
)
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I think it would be valuable to define the Quantity class as a pydantic model:
The shortcut to that would be to define a
__get_pydantic_core_schema__method directly within the Quantity.I did a proof of concept wrapping the Quantity object into a wrapper:
Beta Was this translation helpful? Give feedback.
All reactions