Pydantic-YAML
Pydantic-YAML (version 1.6.0) is an active Python library that extends Pydantic models with YAML reading and writing capabilities. It enables seamless serialization of Pydantic models to YAML strings and deserialization of YAML data back into Pydantic model instances. The library maintains an active release cadence, with ongoing development and support for modern Python and Pydantic versions.
Warnings
- breaking Pydantic-YAML v1 introduces breaking changes regarding the `YamlModel` and `YamlModelMixin` base classes. For Pydantic v2 (and later), these mixin classes have been removed. Users should instead directly use the `parse_yaml_raw_as` and `to_yaml_str` functions.
- gotcha Pydantic-YAML requires an underlying YAML parser (like `ruamel.yaml` or `PyYAML`) to be explicitly installed. Installing `pydantic-yaml` alone will not provide YAML parsing capabilities.
- breaking Support for Python 3.7 has been dropped. The library now requires Python 3.10 or newer.
- gotcha While `pydantic-yaml` leverages Pydantic's JSON dumping internally, direct YAML-specific configuration options (beyond indentation) are limited. More specific YAML configuration is planned for a future major version (v2).
Install
-
pip install pydantic-yaml -
pip install pydantic-yaml[ruamel] -
pip install pydantic-yaml[pyyaml]
Imports
- parse_yaml_raw_as
from pydantic_yaml import parse_yaml_raw_as
- to_yaml_str
from pydantic_yaml import to_yaml_str
- YamlModel
from pydantic_yaml import YamlModel
- YamlModelMixin
from pydantic_yaml import YamlModelMixin
Quickstart
from enum import Enum
from pydantic import BaseModel, validator
from pydantic_yaml import parse_yaml_raw_as, to_yaml_str
class MyEnum(str, Enum):
a = "a"
b = "b"
class InnerModel(BaseModel):
fld: float = 1.0
class MyModel(BaseModel):
x: int = 1
e: MyEnum = MyEnum.a
m: InnerModel = InnerModel()
@validator("x")
def _chk_x(cls, v: int) -> int:
assert v > 0
return v
m1 = MyModel(x=2, e="b", m=InnerModel(fld=1.5))
# Dump to YAML string
yml_string = to_yaml_str(m1, add_comments=True)
print("\n--- Dumped YAML ---\n", yml_string)
# Parse YAML string back into model
m2 = parse_yaml_raw_as(MyModel, yml_string)
print("\n--- Parsed Model ---\n", m2)
assert m1 == m2