### Development Installation of pydantic-yaml Source: https://pydantic-yaml.readthedocs.io/en/latest/installing Installs pydantic-yaml in editable mode for development purposes. This method clones the repository and installs the package along with development and documentation dependencies. ```shell git clone https://github.com/NowanIlfideme/pydantic-yaml.git cd pydantic-yaml pip install -e ".[dev,docs]" ``` -------------------------------- ### Install pydantic-yaml using pip Source: https://pydantic-yaml.readthedocs.io/en/latest/installing Installs the latest stable version of pydantic-yaml and its compatible dependencies (pydantic and ruamel.yaml) using pip. This is the recommended method for most users. ```shell pip install pydantic_yaml ``` -------------------------------- ### Construct Pydantic Model for Example YAML Output (Python) Source: https://pydantic-yaml.readthedocs.io/en/latest/comments Demonstrates using `model_construct()` (for Pydantic v2) to create a model instance with potentially `None` values for fields, useful for generating example YAML structures. This example specifically shows how to create an example YAML with field comments. ```python ex = MyModel.model_construct(c=None) print(to_yaml_str(ex, add_comments="fields-only")) ``` -------------------------------- ### Example YAML Output from Constructed Model Source: https://pydantic-yaml.readthedocs.io/en/latest/comments The YAML output generated from a Pydantic model constructed with `None` values, showing only the field comments. This is useful for creating example configuration files. ```yaml c: # See three? ``` -------------------------------- ### YAML-Specific Formatting Options with Pydantic-YAML Source: https://pydantic-yaml.readthedocs.io/en/latest/index_badge=latest Demonstrates how to control YAML formatting using keyword arguments in `to_yaml_str`, such as `indent`, `map_indent`, and `sequence_indent`. ```python to_yaml_str(model, indent=4) # Makes it wider to_yaml_str(model, map_indent=9, sequence_indent=7) # ... you monster. ``` -------------------------------- ### Basic Pydantic Model Serialization and Deserialization with YAML Source: https://pydantic-yaml.readthedocs.io/en/latest/index Demonstrates how to define a Pydantic model with custom types and validators, then serialize it to YAML and parse YAML back into the model. It also shows how to parse JSON as YAML and generate YAML with comments from docstrings. ```python 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 custom enumeration that is YAML-safe.""" a = "a" b = "b" class InnerModel(BaseModel): """A normal pydantic model that can be used as an inner class.""" fld: float = 1.0 class MyModel(BaseModel): """Our custom Pydantic model.""" x: int = 1 e: MyEnum = MyEnum.a m: InnerModel = InnerModel() @validator("x") def _chk_x(cls, v: int) -> int: # noqa """You can add your normal pydantic validators, like this one.""" assert v > 0 return v m1 = MyModel(x=2, e="b", m=InnerModel(fld=1.5)) # This dumps to YAML and JSON respectivelyyml = to_yaml_str(m1) jsn = m1.json() # This parses YAML as the MyModel type m2 = parse_yaml_raw_as(MyModel, yml) assert m1 == m2 # JSON is also valid YAML, so this works too m3 = parse_yaml_raw_as(MyModel, jsn) assert m1 == m3 # You can also auto-generate comments in YAML from the model docstrings and field descriptions print(to_yaml_str(m1, add_comments=True)) ``` -------------------------------- ### Basic Pydantic Model Serialization and Deserialization with YAML Source: https://pydantic-yaml.readthedocs.io/en/latest/index_badge=latest Demonstrates defining a Pydantic model with enums and nested models, then serializing it to YAML and JSON, and parsing YAML back into the model. It also shows how to generate YAML with comments from docstrings. ```python 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 custom enumeration that is YAML-safe.""" a = "a" b = "b" class InnerModel(BaseModel): """A normal pydantic model that can be used as an inner class.""" fld: float = 1.0 class MyModel(BaseModel): """Our custom Pydantic model.""" x: int = 1 e: MyEnum = MyEnum.a m: InnerModel = InnerModel() @validator("x") def _chk_x(cls, v: int) -> int: # noqa """You can add your normal pydantic validators, like this one.""" assert v > 0 return v m1 = MyModel(x=2, e="b", m=InnerModel(fld=1.5)) # This dumps to YAML and JSON respectively yml = to_yaml_str(m1) jsn = m1.json() # This parses YAML as the MyModel type m2 = parse_yaml_raw_as(MyModel, yml) assert m1 == m2 # JSON is also valid YAML, so this works too m3 = parse_yaml_raw_as(MyModel, jsn) assert m1 == m3 # You can also auto-generate comments in YAML from the model docstrings and field descriptions print(to_yaml_str(m1, add_comments=True)) ``` -------------------------------- ### Using a Custom YAML Instance for Serialization Source: https://pydantic-yaml.readthedocs.io/en/latest/index_badge=latest Shows how to pass a custom `ruamel.yaml.YAML` instance to `to_yaml_file` for more fine-grained control over YAML output, such as setting `default_flow_style`. ```python from ruamel.yaml import YAML my_writer = YAML(typ="safe") my_writer.default_flow_style = True to_yaml_file("foo.yaml", model, custom_yaml_writer=my_writer) ``` -------------------------------- ### Dumping Pydantic Dataclasses to YAML (Pydantic v2+) Source: https://pydantic-yaml.readthedocs.io/en/latest/index_badge=latest Shows how to serialize Pydantic dataclasses to YAML using Pydantic v2 and Pydantic-YAML. It requires Pydantic version 2 or higher and uses `RootModel` for serialization. ```python from pydantic import RootModel from pydantic.dataclasses import dataclass from pydantic.version import VERSION as PYDANTIC_VERSION from pydantic_yaml import to_yaml_str assert PYDANTIC_VERSION >= "2" @dataclass class YourType: foo: str = "bar" obj = YourType(foo="wuz") assert to_yaml_str(RootModel[YourType](obj)) == 'foo: wuz\n' ``` -------------------------------- ### Configuring Pydantic Model JSON Dumping for YAML Source: https://pydantic-yaml.readthedocs.io/en/latest/index_badge=latest Illustrates how to configure Pydantic models to customize JSON dumping, which Pydantic-YAML uses for YAML serialization. This includes overriding `json_dumps`, `json_loads`, and other Pydantic configuration options. ```python class MyModel(BaseModel): # ... class Config: # You can override these fields, which affect JSON and YAML: json_dumps = my_custom_dumper json_loads = lambda x: MyModel() # As well as other Pydantic configuration: allow_mutation = False ``` -------------------------------- ### Generate YAML with Comments from Pydantic Model (Python) Source: https://pydantic-yaml.readthedocs.io/en/latest/comments Illustrates how to convert a Pydantic model instance into a YAML string, including comments derived from field descriptions and model docstrings. Requires `pydantic-yaml` library. ```python from pydantic_yaml import to_yaml_str mdl = MyModel(c=3.14) print(to_yaml_str(mdl, add_comments=True)) ``` -------------------------------- ### Use Docstrings for YAML Comments via model_config (Python) Source: https://pydantic-yaml.readthedocs.io/en/latest/comments Shows how to configure Pydantic models to use docstrings for field descriptions, which are then included as comments in the YAML output. This leverages existing docstrings for documentation. ```python from pydantic import BaseModel, ConfigDict class MyModel(BaseModel): """My custom model.""" # This will become the header! model_config = ConfigDict(use_attribute_docstrings=True) # you can set this in your own BaseModel c: float = 3 """See three?""" # docstring will become description and comment; additional editor benefit! ``` -------------------------------- ### Export YAML with Only Field Comments (Python) Source: https://pydantic-yaml.readthedocs.io/en/latest/comments Shows how to generate YAML output that includes only comments derived from field descriptions, excluding the model's header comment. This focuses on the details of each field. ```python print(to_yaml_str(mdl, add_comments='fields-only')) ``` -------------------------------- ### YAML Output with Model Header and Field Comments Source: https://pydantic-yaml.readthedocs.io/en/latest/comments The resulting YAML output from a Pydantic model when `add_comments=True` is used, showing the model's docstring as a header comment and field descriptions as inline comments. ```yaml # My custom model. c: 3.14 # See three? ``` -------------------------------- ### Export YAML with Only Model Headers (Python) Source: https://pydantic-yaml.readthedocs.io/en/latest/comments Demonstrates how to generate YAML output that includes only the model's docstring as a header comment, excluding field comments. This is useful for summarizing the model's purpose. ```python print(to_yaml_str(mdl, add_comments='models-only')) ``` -------------------------------- ### YAML Output with Only Field Comments Source: https://pydantic-yaml.readthedocs.io/en/latest/comments The YAML output when `add_comments='fields-only'` is specified, showing only the field descriptions as inline comments. ```yaml c: 3.14 # See three? ``` -------------------------------- ### Add Descriptions to Pydantic Model Fields for YAML Comments (Python) Source: https://pydantic-yaml.readthedocs.io/en/latest/comments Demonstrates using `typing.Annotated` and `pydantic.Field` to add descriptions to model fields, which are then exported as comments in the YAML output. This method is preferred for explicit field descriptions. ```python from typing import Annotated from pydantic import BaseModel, Field class MyModel(BaseModel): """My custom model.""" # This will become the header! c: Annotated[float, Field(description="See three?")] = 3 # description will become a comment ``` -------------------------------- ### Custom VersionedModel in Pydantic v1 Source: https://pydantic-yaml.readthedocs.io/en/latest/versioned This Python code defines a custom `VersionedModel` class that extends Pydantic's `BaseModel`. It leverages the `semver` library to handle version parsing and validation, ensuring that the version field adheres to semantic versioning rules and stays within specified limits. The model includes configuration options for minimum and maximum allowed versions and a validator to enforce these constraints. ```python """Versioned model example. Library versions: pydantic<2 semver~=3.0.0 # additional """ import warnings from typing import Optional, Tuple, Type from pydantic import BaseModel, validator from semver import Version # type: ignore def _chk_between(v, lo=None, hi=None): if v is None: return if (hi is not None) and (v > hi): raise ValueError(f"Default version higher than maximum: {v} > {hi}") if (lo is not None) and (v < lo): raise ValueError(f"Default version lower than minimum: {v} < {lo}") def _get_minmax_robust( cls: Type["VersionedModel"], ) -> Tuple[Optional[Version], Optional[Version]]: min_, max_ = None, None for supcls in cls.mro(): Config = getattr(supcls, "Config", None) if Config is not None: if min_ is None: min_ = getattr(Config, "min_version", None) if max_ is None: max_ = getattr(Config, "max_version", None) return min_, max_ class VersionedModel(BaseModel): """Versioned model behavior.""" version: Version class Config: """Pydantic configuration.""" # Allow SemVer arbitrary_types_allowed = True json_encoders = {Version: lambda x: str(x)} # Version limits min_version = Version(0, 0, 0) max_version = None @validator("version", pre=True) def _check_version(cls: Type["VersionedModel"], v) -> Version: # type: ignore """Set version from a string, then check within the limits.""" if not isinstance(v, Version): v = Version.parse(v) min_, max_ = _get_minmax_robust(cls) _chk_between(v, lo=min_, hi=max_) return v def __init_subclass__(cls) -> None: """Set config values.""" # Check Config class types Config = getattr(cls, "Config", None) if Config is not None: # check one field minv = getattr(Config, "min_version", None) if minv is not None: if not isinstance(minv, Version): setattr(Config, "min_version", Version.parse(minv)) # check other field maxv = getattr(Config, "max_version", None) if maxv is not None: if not isinstance(maxv, Version): setattr(Config, "max_version", Version.parse(maxv)) # Check ranges min_, max_ = _get_minmax_robust(cls) if (min_ is not None) and (max_ is not None) and (min_ > max_): raise ValueError(f"Minimum version higher than maximum: {min_!r} > {max_!r}") # Check the default value of the "version" field fld = cls.__fields__["version"] d = fld.default if d is None: pass else: _chk_between(d, lo=min_, hi=max_) warnings.warn( f"Recommended to have `version` be required, but set default {d!r}", UserWarning, ) if not issubclass(fld.type_, Version): raise TypeError(f"Field type for `version` must be Version, got {fld.type_!r}") if __name__ == "__main__": from pydantic_yaml import parse_yaml_raw_as class FooBar(VersionedModel): """Foobar model.""" foo: str class Config: """Pydantic configuration.""" max_version = Version(1) fb = parse_yaml_raw_as( FooBar, """ version: 0.2.0 foo: bar """, ) try: parse_yaml_raw_as( FooBar, """ version: 1.2.0 # higher than v1! foo: bar """, ) except Exception as e: print(e) ``` -------------------------------- ### YAML Output with Only Model Header Source: https://pydantic-yaml.readthedocs.io/en/latest/comments The YAML output when `add_comments='models-only'` is specified, showing only the model's docstring as a header comment. ```yaml # My custom model. c: 3.14 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.