marshmallow
frequenz.quantities.marshmallow ¤
Custom marshmallow fields and schema.
Attributes¤
frequenz.quantities.marshmallow.QUANTITY_FIELD_CLASSES
module-attribute
¤
QUANTITY_FIELD_CLASSES: dict[
type[Quantity], type[Field]
] = {
Current: CurrentField,
Energy: EnergyField,
Frequency: FrequencyField,
Percentage: PercentageField,
Power: PowerField,
Temperature: TemperatureField,
Voltage: VoltageField,
}
Mapping of Quantity subclasses to their corresponding QuantityField subclasses.
This mapping is used in the QuantitySchema
to determine the correct field
class for each Quantity subclass.
The keys are Quantity subclasses (e.g., Percentage, Energy) and the values are the corresponding QuantityField subclasses.
Classes¤
frequenz.quantities.marshmallow.CurrentField ¤
frequenz.quantities.marshmallow.EnergyField ¤
frequenz.quantities.marshmallow.FrequencyField ¤
frequenz.quantities.marshmallow.PercentageField ¤
frequenz.quantities.marshmallow.PowerField ¤
frequenz.quantities.marshmallow.QuantitySchema ¤
Bases: Schema
A schema for quantities.
Example usage:
from dataclasses import dataclass, field
from marshmallow_dataclass import class_schema
from marshmallow.validate import Range
from frequenz.quantities import Percentage, QuantitySchema
from typing import cast
@dataclass
class Config:
percentage_always_as_string: Percentage = field(
default_factory=lambda: Percentage.from_percent(25.0),
metadata={
"metadata": {
"description": "A percentage field",
},
"validate": Range(Percentage.zero(), Percentage.from_percent(100.0)),
"serialize_as_string": True,
},
)
percentage_always_as_float: Percentage = field(
default_factory=lambda: Percentage.from_percent(25.0),
metadata={
"metadata": {
"description": "A percentage field",
},
"validate": Range(Percentage.zero(), Percentage.from_percent(100.0)),
"serialize_as_string": False,
},
)
percentage_serialized_as_schema_default: Percentage = field(
default_factory=lambda: Percentage.from_percent(25.0),
metadata={
"metadata": {
"description": "A percentage field",
},
"validate": Range(Percentage.zero(), Percentage.from_percent(100.0)),
},
)
@classmethod
def load(cls, config: dict[str, Any]) -> "Config":
schema = class_schema(cls, base_schema=QuantitySchema)(
serialize_as_string_default=True # type: ignore[call-arg]
)
return cast(Config, schema.load(config))
Source code in frequenz/quantities/marshmallow.py
Functions¤
__init__ ¤
Initialize the schema with a default serialization format.
PARAMETER | DESCRIPTION |
---|---|
*args
|
Additional positional arguments.
TYPE:
|
serialize_as_string_default
|
Default serialization format for quantities. If True, quantities are serialized as strings with units. If False, quantities are serialized as floats.
TYPE:
|
**kwargs
|
Additional keyword arguments.
TYPE:
|