pydantic-partials


Namepydantic-partials JSON
Version 1.0.6 PyPI version JSON
download
home_pagehttps://github.com/joshorr/pydantic-partials
SummaryPydantic partial model class, with ability to easily dynamically omit fields when serializing a model.
upload_time2024-06-14 22:41:30
maintainerNone
docs_urlNone
authorJosh Orr
requires_python<4.0,>=3.10
licenseNone
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            - [Pydantic Partials](#pydantic-partials)
    * [Documentation](#documentation)
    * [Quick Start](#quick-start)
        + [Install](#install)
        + [Introduction](#introduction)
        + [Basic Example](#basic-example)
        + [Inheritable](#inheritable)
        + [Automatic Partials Configuration](#automatic-partials-configuration)

# Pydantic Partials

An easy way to add or create partials for Pydantic models.

![PythonSupport](https://img.shields.io/static/v1?label=python&message=%203.10|%203.11|%203.12&color=blue?style=flat-square&logo=python)
![PyPI version](https://badge.fury.io/py/xmodel.svg?)

## Documentation

**[📄 Detailed Documentation](https://joshorr.github.io/pydantic-partials/latest/)** | **[🐍 PyPi](https://pypi.org/project/pydantic-partials/)**

[//]: # (--8<-- [start:readme])

## Quick Start

### Install

```shell
poetry install pydantic-partials
```

or

```shell
pip install pydantic-partials
```

### Introduction

You can create from scratch, or convert existing models to be Partials.
The main purpose will be to add to exiting models, and hence the default
behavior of making all non-default fields partials (configurable).

Let's first look at a basic example.

### Basic Example

Very basic example of a simple model follows:

```python
from pydantic_partials import PartialModel, Missing


class MyModel(PartialModel):
    some_attr: str
    another_field: str

# By default, Partial fields without any value will get set to a
# special `Missing` type. Any field that is set to Missing is
# excluded from the model_dump/model_dump_json.
obj = MyModel()
assert obj.some_attr is Missing
assert obj.model_dump() == {}

# You can set the real value at any time, and it will behave like expected.
obj.some_attr = 'hello'
assert obj.some_attr is 'hello'
assert obj.model_dump() == {'some_attr': 'hello'}

# You can always manually set a field to `Missing` directly.
obj.some_attr = Missing

# And now it's removed from the model-dump.
assert obj.model_dump() == {}

# The json dump is also affected in the same way.
assert obj.model_dump_json() == '{}'

# Any non-missing fields will be included when dumping/serializing model.
obj.another_field = 'assigned-value'

# After dumping again, we have `another_field` outputted.
# The `some_attr` field is not present since it's still `Missing`.
assert obj.model_dump() == {'another_field': 'assigned-value'}
```

By default, all fields without a default value will have the ability to be partial,
and can be missing from both validation and serialization.
This includes any inherited Pydantic fields (from a superclass).


### Inheritable

You can inherit from a model to make a partial-version of the inherited fields:

```python
from pydantic_partials import PartialModel, Missing
from pydantic import ValidationError, BaseModel

class TestModel(BaseModel):
    name: str
    value: str
    some_null_by_default_field: str | None = None

try:
    # This should produce an error because
    # `name` and `value`are required fields.
    TestModel()
except ValidationError as e:
    print(f'Pydantic will state `name` + `value` are required: {e}')
else:
    raise Exception('Field `required_decimal` should be required.')

    # We inherit from `TestModel` and add `PartialModel` to the mix.

class PartialTestModel(PartialModel, TestModel):
    pass

# `PartialTestModel` can now be allocated without the required fields.
# Any missing required fields will be marked with the `Missing` value
# and won't be serialized out.
obj = PartialTestModel(name='a-name')

assert obj.name == 'a-name'
assert obj.value is Missing
assert obj.some_null_by_default_field is None

# The `None` field value is still serialized out,
# only fields with a `Missing` value assigned are skipped.
assert obj.model_dump() == {
    'name': 'a-name', 'some_null_by_default_field': None
}
```

Notice that if a field has a default value, it's used instead of marking it as `Missing`.

Also, the `Missing` sentinel value is a separate value vs `None`, allowing one to easily
know if a value is truly just missing or is `None`/`Null`.


### Automatic Partials Configuration

You can turn off automatically applying partials to all non-defaulted fields
via `auto_partials` class argument or modeL_config option:

```python
from pydantic_partials import PartialModel, PartialConfigDict

class TestModel1(PartialModel, auto_partials=False):
    ...

class TestModel2(PartialModel):
    model_config = PartialConfigDict(auto_partials=False)
    ...
```

You can disable this automatic function. This means you have complete control of exactly which field 
can be partial or not.  You can use either the generic `Partial[...]` generic or a union with `MissingType`
to mark a field as a partial field.  The generic simple makes the union to MissingType for you.

Example of disabling auto_partials:

```python
from pydantic_partials import PartialModel, Missing, MissingType, Partial
from decimal import Decimal
from pydantic import ValidationError

class TestModel(PartialModel, auto_partials=False):
    # Can use `Partial` generic type
    partial_int: Partial[int] = Missing
    
    # Or union with `MissingType`
    partial_str: str | MissingType
    
    required_decimal: Decimal
    
try:
    TestModel()
except ValidationError as e:
    print(f'Pydantic will state `required_decimal` is required: {e}')
else:
    raise Exception('Pydantic should have required `required_decimal`.')
    
obj = TestModel(required_decimal='1.34')

# You can find out at any time if a field is missing or not:
assert obj.partial_int is Missing
assert obj.partial_str is Missing

assert obj.required_decimal == Decimal('1.34')
```


[//]: # (--8<-- [end:readme])

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/joshorr/pydantic-partials",
    "name": "pydantic-partials",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.10",
    "maintainer_email": null,
    "keywords": null,
    "author": "Josh Orr",
    "author_email": "josh@orr.blue",
    "download_url": "https://files.pythonhosted.org/packages/0a/e2/97ed2a2a79bb1ad38c5e71e7c947b9615c5d7fefaf629d55dd0df4aea744/pydantic_partials-1.0.6.tar.gz",
    "platform": null,
    "description": "- [Pydantic Partials](#pydantic-partials)\n    * [Documentation](#documentation)\n    * [Quick Start](#quick-start)\n        + [Install](#install)\n        + [Introduction](#introduction)\n        + [Basic Example](#basic-example)\n        + [Inheritable](#inheritable)\n        + [Automatic Partials Configuration](#automatic-partials-configuration)\n\n# Pydantic Partials\n\nAn easy way to add or create partials for Pydantic models.\n\n![PythonSupport](https://img.shields.io/static/v1?label=python&message=%203.10|%203.11|%203.12&color=blue?style=flat-square&logo=python)\n![PyPI version](https://badge.fury.io/py/xmodel.svg?)\n\n## Documentation\n\n**[\ud83d\udcc4 Detailed Documentation](https://joshorr.github.io/pydantic-partials/latest/)** | **[\ud83d\udc0d PyPi](https://pypi.org/project/pydantic-partials/)**\n\n[//]: # (--8<-- [start:readme])\n\n## Quick Start\n\n### Install\n\n```shell\npoetry install pydantic-partials\n```\n\nor\n\n```shell\npip install pydantic-partials\n```\n\n### Introduction\n\nYou can create from scratch, or convert existing models to be Partials.\nThe main purpose will be to add to exiting models, and hence the default\nbehavior of making all non-default fields partials (configurable).\n\nLet's first look at a basic example.\n\n### Basic Example\n\nVery basic example of a simple model follows:\n\n```python\nfrom pydantic_partials import PartialModel, Missing\n\n\nclass MyModel(PartialModel):\n    some_attr: str\n    another_field: str\n\n# By default, Partial fields without any value will get set to a\n# special `Missing` type. Any field that is set to Missing is\n# excluded from the model_dump/model_dump_json.\nobj = MyModel()\nassert obj.some_attr is Missing\nassert obj.model_dump() == {}\n\n# You can set the real value at any time, and it will behave like expected.\nobj.some_attr = 'hello'\nassert obj.some_attr is 'hello'\nassert obj.model_dump() == {'some_attr': 'hello'}\n\n# You can always manually set a field to `Missing` directly.\nobj.some_attr = Missing\n\n# And now it's removed from the model-dump.\nassert obj.model_dump() == {}\n\n# The json dump is also affected in the same way.\nassert obj.model_dump_json() == '{}'\n\n# Any non-missing fields will be included when dumping/serializing model.\nobj.another_field = 'assigned-value'\n\n# After dumping again, we have `another_field` outputted.\n# The `some_attr` field is not present since it's still `Missing`.\nassert obj.model_dump() == {'another_field': 'assigned-value'}\n```\n\nBy default, all fields without a default value will have the ability to be partial,\nand can be missing from both validation and serialization.\nThis includes any inherited Pydantic fields (from a superclass).\n\n\n### Inheritable\n\nYou can inherit from a model to make a partial-version of the inherited fields:\n\n```python\nfrom pydantic_partials import PartialModel, Missing\nfrom pydantic import ValidationError, BaseModel\n\nclass TestModel(BaseModel):\n    name: str\n    value: str\n    some_null_by_default_field: str | None = None\n\ntry:\n    # This should produce an error because\n    # `name` and `value`are required fields.\n    TestModel()\nexcept ValidationError as e:\n    print(f'Pydantic will state `name` + `value` are required: {e}')\nelse:\n    raise Exception('Field `required_decimal` should be required.')\n\n    # We inherit from `TestModel` and add `PartialModel` to the mix.\n\nclass PartialTestModel(PartialModel, TestModel):\n    pass\n\n# `PartialTestModel` can now be allocated without the required fields.\n# Any missing required fields will be marked with the `Missing` value\n# and won't be serialized out.\nobj = PartialTestModel(name='a-name')\n\nassert obj.name == 'a-name'\nassert obj.value is Missing\nassert obj.some_null_by_default_field is None\n\n# The `None` field value is still serialized out,\n# only fields with a `Missing` value assigned are skipped.\nassert obj.model_dump() == {\n    'name': 'a-name', 'some_null_by_default_field': None\n}\n```\n\nNotice that if a field has a default value, it's used instead of marking it as `Missing`.\n\nAlso, the `Missing` sentinel value is a separate value vs `None`, allowing one to easily\nknow if a value is truly just missing or is `None`/`Null`.\n\n\n### Automatic Partials Configuration\n\nYou can turn off automatically applying partials to all non-defaulted fields\nvia `auto_partials` class argument or modeL_config option:\n\n```python\nfrom pydantic_partials import PartialModel, PartialConfigDict\n\nclass TestModel1(PartialModel, auto_partials=False):\n    ...\n\nclass TestModel2(PartialModel):\n    model_config = PartialConfigDict(auto_partials=False)\n    ...\n```\n\nYou can disable this automatic function. This means you have complete control of exactly which field \ncan be partial or not.  You can use either the generic `Partial[...]` generic or a union with `MissingType`\nto mark a field as a partial field.  The generic simple makes the union to MissingType for you.\n\nExample of disabling auto_partials:\n\n```python\nfrom pydantic_partials import PartialModel, Missing, MissingType, Partial\nfrom decimal import Decimal\nfrom pydantic import ValidationError\n\nclass TestModel(PartialModel, auto_partials=False):\n    # Can use `Partial` generic type\n    partial_int: Partial[int] = Missing\n    \n    # Or union with `MissingType`\n    partial_str: str | MissingType\n    \n    required_decimal: Decimal\n    \ntry:\n    TestModel()\nexcept ValidationError as e:\n    print(f'Pydantic will state `required_decimal` is required: {e}')\nelse:\n    raise Exception('Pydantic should have required `required_decimal`.')\n    \nobj = TestModel(required_decimal='1.34')\n\n# You can find out at any time if a field is missing or not:\nassert obj.partial_int is Missing\nassert obj.partial_str is Missing\n\nassert obj.required_decimal == Decimal('1.34')\n```\n\n\n[//]: # (--8<-- [end:readme])\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "Pydantic partial model class, with ability to easily dynamically omit fields when serializing a model.",
    "version": "1.0.6",
    "project_urls": {
        "Homepage": "https://github.com/joshorr/pydantic-partials",
        "Repository": "https://github.com/joshorr/pydantic-partials"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f3f02e62da972ef6a25940fedcfae6d5fa76924af6ebb0cd53fc502d9fa7a99e",
                "md5": "5d49e8d155842546705df50a651e715c",
                "sha256": "6db64ef2d4a9b327c691f8fe350b63ce70f99ffbd39d7a3c009627079c9f798f"
            },
            "downloads": -1,
            "filename": "pydantic_partials-1.0.6-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "5d49e8d155842546705df50a651e715c",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.10",
            "size": 9477,
            "upload_time": "2024-06-14T22:41:28",
            "upload_time_iso_8601": "2024-06-14T22:41:28.545280Z",
            "url": "https://files.pythonhosted.org/packages/f3/f0/2e62da972ef6a25940fedcfae6d5fa76924af6ebb0cd53fc502d9fa7a99e/pydantic_partials-1.0.6-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "0ae297ed2a2a79bb1ad38c5e71e7c947b9615c5d7fefaf629d55dd0df4aea744",
                "md5": "859c6415ddd51cb80e377b71eeb1bbfa",
                "sha256": "9f3bd9d4373003f6c960906220faeef92f5f1d0f8c33d66c61132b98e4c89a36"
            },
            "downloads": -1,
            "filename": "pydantic_partials-1.0.6.tar.gz",
            "has_sig": false,
            "md5_digest": "859c6415ddd51cb80e377b71eeb1bbfa",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.10",
            "size": 8081,
            "upload_time": "2024-06-14T22:41:30",
            "upload_time_iso_8601": "2024-06-14T22:41:30.102036Z",
            "url": "https://files.pythonhosted.org/packages/0a/e2/97ed2a2a79bb1ad38c5e71e7c947b9615c5d7fefaf629d55dd0df4aea744/pydantic_partials-1.0.6.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-14 22:41:30",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "joshorr",
    "github_project": "pydantic-partials",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "pydantic-partials"
}
        
Elapsed time: 0.93887s