Skip to content

yaml_dumpers

Class info

🛈 DocStrings

YAML dump functionality.

dump_yaml

dump_yaml(
    obj: Any,
    class_mappings: dict[type, type] | None = None,
    indent: int | None = None,
    default_flow_style: bool | None = None,
    allow_unicode: bool | None = None,
    **kwargs: Any,
) -> str

Dump a data structure to a YAML string.

Parameters:

Name Type Description Default
obj Any

Object to serialize (also accepts pydantic models)

required
class_mappings dict[type, type] | None

Dict mapping classes to built-in types for YAML representation

None
indent int | None

Indentation level for YAML output

None
default_flow_style bool | None

Whether to use flow style for YAML output

None
allow_unicode bool | None

Whether to allow unicode characters in YAML output

None
kwargs Any

Additional arguments for yaml.dump

{}

Returns:

Type Description
str

YAML string representation

Source code in src/configz/yaml_tools/yaml_dumpers.py
def dump_yaml(
    obj: Any,
    class_mappings: dict[type, type] | None = None,
    indent: int | None = None,
    default_flow_style: bool | None = None,
    allow_unicode: bool | None = None,
    **kwargs: Any,
) -> str:
    """Dump a data structure to a YAML string.

    Args:
        obj: Object to serialize (also accepts pydantic models)
        class_mappings: Dict mapping classes to built-in types for YAML representation
        indent: Indentation level for YAML output
        default_flow_style: Whether to use flow style for YAML output
        allow_unicode: Whether to allow unicode characters in YAML output
        kwargs: Additional arguments for yaml.dump

    Returns:
        YAML string representation
    """
    import yaml

    dumper_cls = utils.create_subclass(yaml.Dumper)
    if class_mappings:
        for class_type, target_type in class_mappings.items():
            map_class_to_builtin_type(dumper_cls, class_type, target_type)
    if importlib.util.find_spec("pydantic"):
        import pydantic

        if isinstance(obj, pydantic.BaseModel):
            obj = obj.model_dump()
    if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
        obj = dataclasses.asdict(obj)
    kwargs = kwargs or {}
    if default_flow_style is not None:
        kwargs["default_flow_style"] = default_flow_style
    return yaml.dump(  # type: ignore[no-any-return]
        obj,
        Dumper=dumper_cls,
        indent=indent,
        allow_unicode=allow_unicode,
        **kwargs,
    )

map_class_to_builtin_type

map_class_to_builtin_type(dumper_class: DumperType, class_type: type, target_type: type) -> None

Maps a Python class to use an existing PyYAML representer for a built-in type.

The original type is preserved, only the representation format is borrowed.

Parameters:

Name Type Description Default
dumper_class DumperType

The YAML Dumper class

required
class_type type

The custom Python class to map

required
target_type type

The built-in type whose representer should be used

required
Source code in src/configz/yaml_tools/yaml_dumpers.py
def map_class_to_builtin_type(
    dumper_class: typedefs.DumperType,
    class_type: type,
    target_type: type,
) -> None:
    """Maps a Python class to use an existing PyYAML representer for a built-in type.

    The original type is preserved, only the representation format is borrowed.

    Args:
        dumper_class: The YAML Dumper class
        class_type: The custom Python class to map
        target_type: The built-in type whose representer should be used
    """
    representer = dumper_class.yaml_representers.get(
        target_type
    ) or dumper_class.yaml_multi_representers.get(target_type)
    if representer is None:
        msg = f"No representer found for type {target_type}"
        raise ValueError(msg)
    dumper_class.add_representer(class_type, representer)