Skip to content

marshmallow

frequenz.quantities.experimental.marshmallow ¤

Custom marshmallow fields and schema.

This module provides custom marshmallow fields for quantities and a QuantitySchema class to be used as base schema for dataclasses containing quantities.

Danger

This module contains experimental features for which the API is not yet stable.

Any module or class in this package may be removed or changed in a future release, even in minor or patch releases.

Attributes¤

frequenz.quantities.experimental.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.experimental.marshmallow.ApparentPowerField ¤

Bases: _QuantityField

Custom field for ApparentPower objects.

Source code in frequenz/quantities/experimental/marshmallow.py
class ApparentPowerField(_QuantityField):
    """Custom field for ApparentPower objects."""

    field_type = ApparentPower

frequenz.quantities.experimental.marshmallow.CurrentField ¤

Bases: _QuantityField

Custom field for Current objects.

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

    field_type = Current

frequenz.quantities.experimental.marshmallow.EnergyField ¤

Bases: _QuantityField

Custom field for Energy objects.

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

    field_type = Energy

frequenz.quantities.experimental.marshmallow.FrequencyField ¤

Bases: _QuantityField

Custom field for Frequency objects.

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

    field_type = Frequency

frequenz.quantities.experimental.marshmallow.PercentageField ¤

Bases: _QuantityField

Custom field for Percentage objects.

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

    field_type = Percentage

frequenz.quantities.experimental.marshmallow.PowerField ¤

Bases: _QuantityField

Custom field for Power objects.

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

    field_type = Power

frequenz.quantities.experimental.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
from frequenz.quantities.experimental.marshmallow import 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/experimental/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
    from frequenz.quantities.experimental.marshmallow import 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/experimental/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.experimental.marshmallow.ReactivePowerField ¤

Bases: _QuantityField

Custom field for ReactivePower objects.

Source code in frequenz/quantities/experimental/marshmallow.py
class ReactivePowerField(_QuantityField):
    """Custom field for ReactivePower objects."""

    field_type = ReactivePower

frequenz.quantities.experimental.marshmallow.TemperatureField ¤

Bases: _QuantityField

Custom field for Temperature objects.

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

    field_type = Temperature

frequenz.quantities.experimental.marshmallow.VoltageField ¤

Bases: _QuantityField

Custom field for Voltage objects.

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

    field_type = Voltage