Pydantic-YAML

1.6.0 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This example demonstrates how to define a Pydantic model with nested structures and enums, then serialize an instance to a YAML string, and finally deserialize that YAML string back into a Pydantic model using `pydantic-yaml`'s `to_yaml_str` and `parse_yaml_raw_as` functions. It also shows how Pydantic validators are preserved.

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

view raw JSON →