Skip to content

Yaml

yaml

YAML serialization helpers and flow-style wrappers for flepimop2.

Flepimop2YamlDumper

Bases: SafeDumper

Project YAML dumper with support for per-subtree flow-style wrappers.

increase_indent(flow=False, indentless=False)

Indent nested block sequences while preserving top-level list-view sections.

PyYAML's default "indentless" mode emits sequences under mapping keys as:

key:
- value

That is compact for top-level normalized sections such as systems, but it is harder to scan for nested arrays. Keep the top-level behavior and render nested sequences as:

key:
  - value
Source code in src/flepimop2/yaml.py
@override
def increase_indent(self, flow: bool = False, indentless: bool = False) -> None:
    """
    Indent nested block sequences while preserving top-level list-view sections.

    PyYAML's default "indentless" mode emits sequences under mapping keys as:

        key:
        - value

    That is compact for top-level normalized sections such as `systems`, but
    it is harder to scan for nested arrays. Keep the top-level behavior and
    render nested sequences as:

        key:
          - value
    """
    super().increase_indent(
        flow=flow,
        indentless=indentless if self.indent == 0 else False,
    )

YamlFormattedMapping(values=(), *, flow_style=None)

Bases: UserDict[K, V]

Dict wrapper that can request a specific YAML flow style.

Examples:

>>> wrapped = YamlFormattedMapping({"a": 1}, flow_style=True)
>>> dict(wrapped)
{'a': 1}
>>> wrapped.flow_style
True

Initialize the mapping wrapper with optional flow-style metadata.

Source code in src/flepimop2/yaml.py
def __init__(
    self,
    values: Mapping[K, V] | Iterable[tuple[K, V]] = (),
    *,
    flow_style: bool | None = None,
) -> None:
    """Initialize the mapping wrapper with optional flow-style metadata."""
    super().__init__(values)
    self.flow_style = flow_style

YamlFormattedSequence(values=(), *, flow_style=None)

Bases: UserList[T]

List wrapper that can request a specific YAML flow style.

Examples:

>>> wrapped = YamlFormattedSequence((1, 2), flow_style=True)
>>> list(wrapped)
[1, 2]
>>> wrapped.flow_style
True

Initialize the sequence wrapper with optional flow-style metadata.

Source code in src/flepimop2/yaml.py
def __init__(
    self,
    values: Iterable[T] = (),
    *,
    flow_style: bool | None = None,
) -> None:
    """Initialize the sequence wrapper with optional flow-style metadata."""
    super().__init__(values)
    self.flow_style = flow_style

YamlSerializableBaseModel

Bases: BaseModel

Base model with YAML serialization support.

Example

class DemoModel(YamlSerializableBaseModel): ... name: str payload = DemoModel(name="demo").safe_dump() print(payload, end="") name: demo DemoModel.safe_load(payload) DemoModel(name='demo')

document_start_marker property

Return whether this model emits an explicit document-start marker.

Returns:

Type Description
bool

Whether --- is emitted by default when dumping this model.

from_yaml(file, encoding='utf-8', **kwargs) classmethod

Deserialize a YAML file to an instance of the model.

Parameters:

Name Type Description Default
file Path

Path to the YAML file to read.

required
encoding str

Encoding of the YAML file.

'utf-8'
**kwargs Any

Additional keyword arguments to pass to Path.read_text.

{}

Returns:

Type Description
Self

An instance of the model.

Source code in src/flepimop2/yaml.py
@classmethod
def from_yaml(cls, file: Path, encoding: str = "utf-8", **kwargs: Any) -> Self:
    """
    Deserialize a YAML file to an instance of the model.

    Args:
        file: Path to the YAML file to read.
        encoding: Encoding of the YAML file.
        **kwargs: Additional keyword arguments to pass to `Path.read_text`.

    Returns:
        An instance of the model.
    """
    return cls.safe_load(file.read_text(encoding=encoding, **kwargs))

safe_dump(*, explicit_start=None)

Serialize the model to a YAML document.

Parameters:

Name Type Description Default
explicit_start bool | None

Whether to emit an explicit --- document start. By default, preserve the marker from the loaded YAML document.

None

Returns:

Type Description
str

The serialized YAML document.

Examples:

>>> class DemoModel(YamlSerializableBaseModel):
...     name: str
>>> print(DemoModel(name="demo").safe_dump(), end="")
name: demo
Source code in src/flepimop2/yaml.py
def safe_dump(self, *, explicit_start: bool | None = None) -> str:
    """
    Serialize the model to a YAML document.

    Args:
        explicit_start: Whether to emit an explicit `---` document start.
            By default, preserve the marker from the loaded YAML document.

    Returns:
        The serialized YAML document.

    Examples:
        >>> class DemoModel(YamlSerializableBaseModel):
        ...     name: str
        >>> print(DemoModel(name="demo").safe_dump(), end="")
        name: demo
    """
    return yaml_dump(
        self.to_yaml_data(),
        Dumper=Flepimop2YamlDumper,
        default_flow_style=False,
        explicit_start=self._document_start_marker
        if explicit_start is None
        else explicit_start,
        sort_keys=False,
    )

safe_load(contents) classmethod

Deserialize YAML text to an instance of the model.

Parameters:

Name Type Description Default
contents str

The YAML document to deserialize.

required

Returns:

Type Description
Self

An instance of the model.

Examples:

>>> class DemoModel(YamlSerializableBaseModel):
...     name: str
>>> DemoModel.safe_load("name: demo")
DemoModel(name='demo')
Source code in src/flepimop2/yaml.py
@classmethod
def safe_load(cls, contents: str) -> Self:
    """
    Deserialize YAML text to an instance of the model.

    Args:
        contents: The YAML document to deserialize.

    Returns:
        An instance of the model.

    Examples:
        >>> class DemoModel(YamlSerializableBaseModel):
        ...     name: str
        >>> DemoModel.safe_load("name: demo")
        DemoModel(name='demo')
    """
    model = cls.model_validate(yaml_safe_load(contents))
    model.set_document_start_marker(value=_has_explicit_document_start(contents))
    return model

set_document_start_marker(*, value)

Set whether this model should emit an explicit document-start marker.

Parameters:

Name Type Description Default
value bool

Whether to emit --- by default when dumping this model.

required
Source code in src/flepimop2/yaml.py
def set_document_start_marker(self, *, value: bool) -> None:
    """
    Set whether this model should emit an explicit document-start marker.

    Args:
        value: Whether to emit `---` by default when dumping this model.
    """
    self._document_start_marker = value

to_yaml(file, encoding='utf-8', *, explicit_start=None, **kwargs)

Serialize the model to a YAML file.

Parameters:

Name Type Description Default
file Path

Path to the YAML file to write.

required
encoding str

Encoding of the YAML file.

'utf-8'
explicit_start bool | None

Whether to emit an explicit --- document start. By default, preserve the marker from the loaded YAML document.

None
**kwargs Any

Additional keyword arguments to pass to Path.write_text.

{}
Source code in src/flepimop2/yaml.py
def to_yaml(
    self,
    file: Path,
    encoding: str = "utf-8",
    *,
    explicit_start: bool | None = None,
    **kwargs: Any,
) -> None:
    """
    Serialize the model to a YAML file.

    Args:
        file: Path to the YAML file to write.
        encoding: Encoding of the YAML file.
        explicit_start: Whether to emit an explicit `---` document start.
            By default, preserve the marker from the loaded YAML document.
        **kwargs: Additional keyword arguments to pass to `Path.write_text`.
    """
    file.write_text(
        self.safe_dump(explicit_start=explicit_start),
        encoding=encoding,
        **kwargs,
    )

to_yaml_data()

Convert the model into YAML-ready Python objects.

Subclasses can override this method to control both the serialized representation and any YAML style wrappers used by the project dumper.

Returns:

Type Description
object

A YAML-ready representation of the model.

Examples:

>>> class DemoModel(YamlSerializableBaseModel):
...     name: str
...     dims: tuple[int, int]
>>> DemoModel(name="demo", dims=(1, 2)).to_yaml_data()
{'name': 'demo', 'dims': [1, 2]}
Source code in src/flepimop2/yaml.py
def to_yaml_data(self) -> object:
    """
    Convert the model into YAML-ready Python objects.

    Subclasses can override this method to control both the serialized
    representation and any YAML style wrappers used by the project dumper.

    Returns:
        A YAML-ready representation of the model.

    Examples:
        >>> class DemoModel(YamlSerializableBaseModel):
        ...     name: str
        ...     dims: tuple[int, int]
        >>> DemoModel(name="demo", dims=(1, 2)).to_yaml_data()
        {'name': 'demo', 'dims': [1, 2]}
    """
    return _model_to_yaml_mapping(self)

yaml_mapping(values=(), *, flow_style=None)

Wrap a mapping with YAML style metadata.

Module authors can return this from to_yaml_data() when a specific subtree should use flow style, e.g. {a: 1, b: 2}.

Returns:

Type Description
YamlFormattedMapping[K, V]

A mapping wrapper carrying the requested YAML flow-style hint.

Examples:

>>> wrapped = yaml_mapping({"kind": "demo"}, flow_style=True)
>>> dict(wrapped)
{'kind': 'demo'}
>>> wrapped.flow_style
True
Source code in src/flepimop2/yaml.py
def yaml_mapping(
    values: Mapping[K, V] | Iterable[tuple[K, V]] = (),
    *,
    flow_style: bool | None = None,
) -> YamlFormattedMapping[K, V]:
    """
    Wrap a mapping with YAML style metadata.

    Module authors can return this from `to_yaml_data()` when a specific
    subtree should use flow style, e.g. `{a: 1, b: 2}`.

    Returns:
        A mapping wrapper carrying the requested YAML flow-style hint.

    Examples:
        >>> wrapped = yaml_mapping({"kind": "demo"}, flow_style=True)
        >>> dict(wrapped)
        {'kind': 'demo'}
        >>> wrapped.flow_style
        True
    """
    return YamlFormattedMapping(values, flow_style=flow_style)

yaml_sequence(values=(), *, flow_style=None)

Wrap a sequence with YAML style metadata.

Module authors can return this from to_yaml_data() when a specific subtree should use flow style, e.g. [a, b, c].

Returns:

Type Description
YamlFormattedSequence[T]

A sequence wrapper carrying the requested YAML flow-style hint.

Examples:

>>> wrapped = yaml_sequence(("a", "b"), flow_style=True)
>>> list(wrapped)
['a', 'b']
>>> wrapped.flow_style
True
Source code in src/flepimop2/yaml.py
def yaml_sequence(
    values: Iterable[T] = (),
    *,
    flow_style: bool | None = None,
) -> YamlFormattedSequence[T]:
    """
    Wrap a sequence with YAML style metadata.

    Module authors can return this from `to_yaml_data()` when a specific
    subtree should use flow style, e.g. `[a, b, c]`.

    Returns:
        A sequence wrapper carrying the requested YAML flow-style hint.

    Examples:
        >>> wrapped = yaml_sequence(("a", "b"), flow_style=True)
        >>> list(wrapped)
        ['a', 'b']
        >>> wrapped.flow_style
        True
    """
    return YamlFormattedSequence(values, flow_style=flow_style)