pydantic-yaml


Namepydantic-yaml JSON
Version 1.3.0 PyPI version JSON
download
home_pageNone
SummaryAdds some YAML functionality to the excellent `pydantic` library.
upload_time2024-03-29 20:24:45
maintainerNone
docs_urlNone
authorNone
requires_python>=3.8
licenseMIT License Copyright (c) 2020 Anatoly Makarevich Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords pydantic yaml
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Pydantic-YAML

[![PyPI version](https://badge.fury.io/py/pydantic-yaml.svg)](https://badge.fury.io/py/pydantic-yaml) [![Documentation Status](https://readthedocs.org/projects/pydantic-yaml/badge/?version=latest)](https://pydantic-yaml.readthedocs.io/en/latest/?badge=latest)
 [![Unit Tests](https://github.com/NowanIlfideme/pydantic-yaml/actions/workflows/python-testing.yml/badge.svg)](https://github.com/NowanIlfideme/pydantic-yaml/actions/workflows/python-testing.yml)

Pydantic-YAML adds YAML capabilities to [Pydantic](https://pydantic-docs.helpmanual.io/),
which is an _excellent_ Python library for data validation and settings management.
If you aren't familiar with Pydantic, I would suggest you first check out their
[docs](https://pydantic-docs.helpmanual.io/).

[Documentation on ReadTheDocs.org](https://pydantic-yaml.readthedocs.io/en/latest/)

## Basic Usage

```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

```

With Pydantic v2, you can also dump dataclasses:

```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'
```

## Configuration

Currently we use the JSON dumping of Pydantic to perform most of the magic.

This uses the `Config` inner class,
[as in Pydantic](https://pydantic-docs.helpmanual.io/usage/model_config/):

```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
```

You can control some YAML-specfic options via the keyword options:

```python
to_yaml_str(model, indent=4)  # Makes it wider
to_yaml_str(model, map_indent=9, sequence_indent=7)  # ... you monster.
```

You can additionally pass your own `YAML` instance:

```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)
```

A separate configuration for YAML specifically will be added later, likely in v2.

## Breaking Changes for `pydantic-yaml` V1

The API for `pydantic-yaml` version 1.0.0 has been greatly simplified!

### Mixin Class

This functionality has currently been removed!
`YamlModel` and `YamlModelMixin` base classes are no longer needed.
The plan is to re-add it before v1 fully releases,
to allow the `.yaml()` or `.parse_*()` methods.
However, this will be availble only for `pydantic<2`.

### Versioned Models

This functionality has been removed, as it's questionably useful for most users.
There is an [example in the docs](versioned.md) that's available.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "pydantic-yaml",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "pydantic, yaml",
    "author": null,
    "author_email": "NowanIlfideme <git@nowan.dev>",
    "download_url": "https://files.pythonhosted.org/packages/3f/e5/3de82d7e0b9e7cdb8bb911f1ff46a5bed3f84853950492722f6227d55896/pydantic_yaml-1.3.0.tar.gz",
    "platform": null,
    "description": "# Pydantic-YAML\n\n[![PyPI version](https://badge.fury.io/py/pydantic-yaml.svg)](https://badge.fury.io/py/pydantic-yaml) [![Documentation Status](https://readthedocs.org/projects/pydantic-yaml/badge/?version=latest)](https://pydantic-yaml.readthedocs.io/en/latest/?badge=latest)\n [![Unit Tests](https://github.com/NowanIlfideme/pydantic-yaml/actions/workflows/python-testing.yml/badge.svg)](https://github.com/NowanIlfideme/pydantic-yaml/actions/workflows/python-testing.yml)\n\nPydantic-YAML adds YAML capabilities to [Pydantic](https://pydantic-docs.helpmanual.io/),\nwhich is an _excellent_ Python library for data validation and settings management.\nIf you aren't familiar with Pydantic, I would suggest you first check out their\n[docs](https://pydantic-docs.helpmanual.io/).\n\n[Documentation on ReadTheDocs.org](https://pydantic-yaml.readthedocs.io/en/latest/)\n\n## Basic Usage\n\n```python\nfrom enum import Enum\nfrom pydantic import BaseModel, validator\nfrom pydantic_yaml import parse_yaml_raw_as, to_yaml_str\n\nclass MyEnum(str, Enum):\n    \"\"\"A custom enumeration that is YAML-safe.\"\"\"\n\n    a = \"a\"\n    b = \"b\"\n\nclass InnerModel(BaseModel):\n    \"\"\"A normal pydantic model that can be used as an inner class.\"\"\"\n\n    fld: float = 1.0\n\nclass MyModel(BaseModel):\n    \"\"\"Our custom Pydantic model.\"\"\"\n\n    x: int = 1\n    e: MyEnum = MyEnum.a\n    m: InnerModel = InnerModel()\n\n    @validator(\"x\")\n    def _chk_x(cls, v: int) -> int:  # noqa\n        \"\"\"You can add your normal pydantic validators, like this one.\"\"\"\n        assert v > 0\n        return v\n\nm1 = MyModel(x=2, e=\"b\", m=InnerModel(fld=1.5))\n\n# This dumps to YAML and JSON respectively\nyml = to_yaml_str(m1)\njsn = m1.json()\n\n# This parses YAML as the MyModel type\nm2 = parse_yaml_raw_as(MyModel, yml)\nassert m1 == m2\n\n# JSON is also valid YAML, so this works too\nm3 = parse_yaml_raw_as(MyModel, jsn)\nassert m1 == m3\n\n```\n\nWith Pydantic v2, you can also dump dataclasses:\n\n```python\nfrom pydantic import RootModel\nfrom pydantic.dataclasses import dataclass\nfrom pydantic.version import VERSION as PYDANTIC_VERSION\nfrom pydantic_yaml import to_yaml_str\n\nassert PYDANTIC_VERSION >= \"2\"\n\n@dataclass\nclass YourType:\n    foo: str = \"bar\"\n\nobj = YourType(foo=\"wuz\")\nassert to_yaml_str(RootModel[YourType](obj)) == 'foo: wuz\\n'\n```\n\n## Configuration\n\nCurrently we use the JSON dumping of Pydantic to perform most of the magic.\n\nThis uses the `Config` inner class,\n[as in Pydantic](https://pydantic-docs.helpmanual.io/usage/model_config/):\n\n```python\nclass MyModel(BaseModel):\n    # ...\n    class Config:\n        # You can override these fields, which affect JSON and YAML:\n        json_dumps = my_custom_dumper\n        json_loads = lambda x: MyModel()\n        # As well as other Pydantic configuration:\n        allow_mutation = False\n```\n\nYou can control some YAML-specfic options via the keyword options:\n\n```python\nto_yaml_str(model, indent=4)  # Makes it wider\nto_yaml_str(model, map_indent=9, sequence_indent=7)  # ... you monster.\n```\n\nYou can additionally pass your own `YAML` instance:\n\n```python\nfrom ruamel.yaml import YAML\nmy_writer = YAML(typ=\"safe\")\nmy_writer.default_flow_style = True\nto_yaml_file(\"foo.yaml\", model, custom_yaml_writer=my_writer)\n```\n\nA separate configuration for YAML specifically will be added later, likely in v2.\n\n## Breaking Changes for `pydantic-yaml` V1\n\nThe API for `pydantic-yaml` version 1.0.0 has been greatly simplified!\n\n### Mixin Class\n\nThis functionality has currently been removed!\n`YamlModel` and `YamlModelMixin` base classes are no longer needed.\nThe plan is to re-add it before v1 fully releases,\nto allow the `.yaml()` or `.parse_*()` methods.\nHowever, this will be availble only for `pydantic<2`.\n\n### Versioned Models\n\nThis functionality has been removed, as it's questionably useful for most users.\nThere is an [example in the docs](versioned.md) that's available.\n",
    "bugtrack_url": null,
    "license": "MIT License  Copyright (c) 2020 Anatoly Makarevich  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ",
    "summary": "Adds some YAML functionality to the excellent `pydantic` library.",
    "version": "1.3.0",
    "project_urls": {
        "docs": "https://pydantic-yaml.readthedocs.io/en/latest/",
        "github": "https://github.com/NowanIlfideme/pydantic-yaml"
    },
    "split_keywords": [
        "pydantic",
        " yaml"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "fae756aa088de31bac787d69fea305c24b06931cb531d8d3e579da585aef06e6",
                "md5": "27deaae31873f5684465c2bb05fca9bc",
                "sha256": "0684255a860522c9226d4eff5c0e8ba44339683b5c5fa79fac4470c0e3821911"
            },
            "downloads": -1,
            "filename": "pydantic_yaml-1.3.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "27deaae31873f5684465c2bb05fca9bc",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 17963,
            "upload_time": "2024-03-29T20:24:43",
            "upload_time_iso_8601": "2024-03-29T20:24:43.265779Z",
            "url": "https://files.pythonhosted.org/packages/fa/e7/56aa088de31bac787d69fea305c24b06931cb531d8d3e579da585aef06e6/pydantic_yaml-1.3.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3fe53de82d7e0b9e7cdb8bb911f1ff46a5bed3f84853950492722f6227d55896",
                "md5": "5a4869e23c780ab11a7993a29d1fdc1f",
                "sha256": "5671c9ef1731570aa2644432ae1e2dd34c406bd4a0a393df622f6b897a88df83"
            },
            "downloads": -1,
            "filename": "pydantic_yaml-1.3.0.tar.gz",
            "has_sig": false,
            "md5_digest": "5a4869e23c780ab11a7993a29d1fdc1f",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 21257,
            "upload_time": "2024-03-29T20:24:45",
            "upload_time_iso_8601": "2024-03-29T20:24:45.271799Z",
            "url": "https://files.pythonhosted.org/packages/3f/e5/3de82d7e0b9e7cdb8bb911f1ff46a5bed3f84853950492722f6227d55896/pydantic_yaml-1.3.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-29 20:24:45",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "NowanIlfideme",
    "github_project": "pydantic-yaml",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "pydantic-yaml"
}
        
Elapsed time: 0.29894s