Skip to content

marshmallow

frequenz.quantities.marshmallow ¤

Custom marshmallow fields and schema.

Attributes¤

frequenz.quantities.marshmallow.QUANTITY_FIELD_CLASSES module-attribute ¤

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 ¤

Bases: _QuantityField

Custom field for Current objects.

Source code in frequenz/quantities/marshmallow.py
class CurrentField(_QuantityField):
    """Custom field for Current objects."""

    field_type = Current

frequenz.quantities.marshmallow.EnergyField ¤

Bases: _QuantityField

Custom field for Energy objects.

Source code in frequenz/quantities/marshmallow.py
class EnergyField(_QuantityField):
    """Custom field for Energy objects."""

    field_type = Energy

frequenz.quantities.marshmallow.FrequencyField ¤

Bases: _QuantityField

Custom field for Frequency objects.

Source code in frequenz/quantities/marshmallow.py
class FrequencyField(_QuantityField):
    """Custom field for Frequency objects."""

    field_type = Frequency

frequenz.quantities.marshmallow.PercentageField ¤

Bases: _QuantityField

Custom field for Percentage objects.

Source code in frequenz/quantities/marshmallow.py
class PercentageField(_QuantityField):
    """Custom field for Percentage objects."""

    field_type = Percentage

frequenz.quantities.marshmallow.PowerField ¤

Bases: _QuantityField

Custom field for Power objects.

Source code in frequenz/quantities/marshmallow.py
class PowerField(_QuantityField):
    """Custom field for Power objects."""

    field_type = Power

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
class QuantitySchema(Schema):
    """A schema for quantities.

    Example usage:

    ```python
    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))
    ```
    """

    TYPE_MAPPING: dict[type[Quantity], type[fields.Field]] = QUANTITY_FIELD_CLASSES

    def __init__(
        self, *args: Any, serialize_as_string_default: bool = False, **kwargs: Any
    ) -> None:
        """
        Initialize the schema with a default serialization format.

        Args:
            *args: Additional positional arguments.
            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.
            **kwargs: Additional keyword arguments.
        """
        super().__init__(*args, **kwargs)
        self.context["serialize_as_string_default"] = serialize_as_string_default
Functions¤
__init__ ¤
__init__(
    *args: Any,
    serialize_as_string_default: bool = False,
    **kwargs: Any
) -> None

Initialize the schema with a default serialization format.

PARAMETER DESCRIPTION
*args

Additional positional arguments.

TYPE: Any DEFAULT: ()

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: bool DEFAULT: False

**kwargs

Additional keyword arguments.

TYPE: Any DEFAULT: {}

Source code in frequenz/quantities/marshmallow.py
def __init__(
    self, *args: Any, serialize_as_string_default: bool = False, **kwargs: Any
) -> None:
    """
    Initialize the schema with a default serialization format.

    Args:
        *args: Additional positional arguments.
        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.
        **kwargs: Additional keyword arguments.
    """
    super().__init__(*args, **kwargs)
    self.context["serialize_as_string_default"] = serialize_as_string_default

frequenz.quantities.marshmallow.TemperatureField ¤

Bases: _QuantityField

Custom field for Temperature objects.

Source code in frequenz/quantities/marshmallow.py
class TemperatureField(_QuantityField):
    """Custom field for Temperature objects."""

    field_type = Temperature

frequenz.quantities.marshmallow.VoltageField ¤

Bases: _QuantityField

Custom field for Voltage objects.

Source code in frequenz/quantities/marshmallow.py
class VoltageField(_QuantityField):
    """Custom field for Voltage objects."""

    field_type = Voltage