pydantic-collections


Namepydantic-collections JSON
Version 0.6.0 PyPI version JSON
download
home_pagehttps://github.com/romis2012/pydantic-collections
SummaryCollections of pydantic models
upload_time2024-07-09 10:43:24
maintainerNone
docs_urlNone
authorRoman Snegirev
requires_pythonNone
licenseApache 2
keywords python pydantic validation parsing serialization models
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # pydantic-collections

[![CI](https://github.com/romis2012/pydantic-collections/actions/workflows/ci.yml/badge.svg)](https://github.com/romis2012/pydantic-collections/actions/workflows/ci.yml)
[![Coverage Status](https://codecov.io/gh/romis2012/pydantic-collections/branch/master/graph/badge.svg)](https://codecov.io/gh/romis2012/pydantic-collections)
[![PyPI version](https://badge.fury.io/py/pydantic-collections.svg)](https://pypi.python.org/pypi/pydantic-collections)

The `pydantic-collections` package provides `BaseCollectionModel` class that allows you 
to manipulate collections of [pydantic](https://github.com/samuelcolvin/pydantic) models 
(and any other types supported by pydantic).


## Requirements
- Python>=3.7
- pydantic>=1.8.2,<3.0


## Installation

```
pip install pydantic-collections
```

## Usage

#### Basic usage
```python

from datetime import datetime

from pydantic import BaseModel
from pydantic_collections import BaseCollectionModel


class User(BaseModel):
    id: int
    name: str
    birth_date: datetime


class UserCollection(BaseCollectionModel[User]):
    pass


 user_data = [
        {'id': 1, 'name': 'Bender', 'birth_date': '2010-04-01T12:59:59'},
        {'id': 2, 'name': 'Balaganov', 'birth_date': '2020-04-01T12:59:59'},
    ]

users = UserCollection(user_data)

print(users)
#> UserCollection([User(id=1, name='Bender', birth_date=datetime.datetime(2010, 4, 1, 12, 59, 59)), User(id=2, name='Balaganov', birth_date=datetime.datetime(2020, 4, 1, 12, 59, 59))])

print(users.dict())  # pydantic v1.x
print(users.model_dump())  # pydantic v2.x
#> [{'id': 1, 'name': 'Bender', 'birth_date': datetime.datetime(2010, 4, 1, 12, 59, 59)}, {'id': 2, 'name': 'Balaganov', 'birth_date': datetime.datetime(2020, 4, 1, 12, 59, 59)}]

print(users.json()) # pydantic v1.x
print(users.model_dump_json()) # pydantic v2.x
#> [{"id": 1, "name": "Bender", "birth_date": "2010-04-01T12:59:59"}, {"id": 2, "name": "Balaganov", "birth_date": "2020-04-01T12:59:59"}]
```

#### Strict assignment validation

By default `BaseCollectionModel` has a strict assignment check
```python
...
users = UserCollection()
users.append(User(id=1, name='Bender', birth_date=datetime.utcnow()))  # OK
users.append({'id': 1, 'name': 'Bender', 'birth_date': '2010-04-01T12:59:59'})
#> pydantic.error_wrappers.ValidationError: 1 validation error for UserCollection
#> __root__ -> 2
#>  instance of User expected (type=type_error.arbitrary_type; expected_arbitrary_type=User)
```

This behavior can be changed via Model Config

Pydantic v1.x
```python
from pydantic_collections import BaseCollectionModel
...
class UserCollection(BaseCollectionModel[User]):
    class Config:
        validate_assignment_strict = False
```

Pydantic v2.x
```python
from pydantic_collections import BaseCollectionModel, CollectionModelConfig
...
class UserCollection(BaseCollectionModel[User]):
    model_config = CollectionModelConfig(validate_assignment_strict=False)
```

```python
users = UserCollection()
users.append({'id': 1, 'name': 'Bender', 'birth_date': '2010-04-01T12:59:59'})  # OK
assert users[0].__class__ is User
assert users[0].id == 1
```

#### Using as a model field

`BaseCollectionModel` is a subclass of `BaseModel`, so you can use it as a model field
```python
...
class UserContainer(BaseModel):
    users: UserCollection = []
        
data = {
    'users': [
        {'id': 1, 'name': 'Bender', 'birth_date': '2010-04-01T12:59:59'},
        {'id': 2, 'name': 'Balaganov', 'birth_date': '2020-04-01T12:59:59'},
    ]
}

container = UserContainer(**data)
container.users.append(User(...))
...
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/romis2012/pydantic-collections",
    "name": "pydantic-collections",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": "python pydantic validation parsing serialization models",
    "author": "Roman Snegirev",
    "author_email": "snegiryev@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/68/b3/ca1ba73ce72fc36b950bcc8d499a7085c8709f0a1a17f1e977bcd1ed5e88/pydantic_collections-0.6.0.tar.gz",
    "platform": null,
    "description": "# pydantic-collections\n\n[![CI](https://github.com/romis2012/pydantic-collections/actions/workflows/ci.yml/badge.svg)](https://github.com/romis2012/pydantic-collections/actions/workflows/ci.yml)\n[![Coverage Status](https://codecov.io/gh/romis2012/pydantic-collections/branch/master/graph/badge.svg)](https://codecov.io/gh/romis2012/pydantic-collections)\n[![PyPI version](https://badge.fury.io/py/pydantic-collections.svg)](https://pypi.python.org/pypi/pydantic-collections)\n\nThe `pydantic-collections` package provides `BaseCollectionModel` class that allows you \nto manipulate collections of [pydantic](https://github.com/samuelcolvin/pydantic) models \n(and any other types supported by pydantic).\n\n\n## Requirements\n- Python>=3.7\n- pydantic>=1.8.2,<3.0\n\n\n## Installation\n\n```\npip install pydantic-collections\n```\n\n## Usage\n\n#### Basic usage\n```python\n\nfrom datetime import datetime\n\nfrom pydantic import BaseModel\nfrom pydantic_collections import BaseCollectionModel\n\n\nclass User(BaseModel):\n    id: int\n    name: str\n    birth_date: datetime\n\n\nclass UserCollection(BaseCollectionModel[User]):\n    pass\n\n\n user_data = [\n        {'id': 1, 'name': 'Bender', 'birth_date': '2010-04-01T12:59:59'},\n        {'id': 2, 'name': 'Balaganov', 'birth_date': '2020-04-01T12:59:59'},\n    ]\n\nusers = UserCollection(user_data)\n\nprint(users)\n#> UserCollection([User(id=1, name='Bender', birth_date=datetime.datetime(2010, 4, 1, 12, 59, 59)), User(id=2, name='Balaganov', birth_date=datetime.datetime(2020, 4, 1, 12, 59, 59))])\n\nprint(users.dict())  # pydantic v1.x\nprint(users.model_dump())  # pydantic v2.x\n#> [{'id': 1, 'name': 'Bender', 'birth_date': datetime.datetime(2010, 4, 1, 12, 59, 59)}, {'id': 2, 'name': 'Balaganov', 'birth_date': datetime.datetime(2020, 4, 1, 12, 59, 59)}]\n\nprint(users.json()) # pydantic v1.x\nprint(users.model_dump_json()) # pydantic v2.x\n#> [{\"id\": 1, \"name\": \"Bender\", \"birth_date\": \"2010-04-01T12:59:59\"}, {\"id\": 2, \"name\": \"Balaganov\", \"birth_date\": \"2020-04-01T12:59:59\"}]\n```\n\n#### Strict assignment validation\n\nBy default `BaseCollectionModel` has a strict assignment check\n```python\n...\nusers = UserCollection()\nusers.append(User(id=1, name='Bender', birth_date=datetime.utcnow()))  # OK\nusers.append({'id': 1, 'name': 'Bender', 'birth_date': '2010-04-01T12:59:59'})\n#> pydantic.error_wrappers.ValidationError: 1 validation error for UserCollection\n#> __root__ -> 2\n#>  instance of User expected (type=type_error.arbitrary_type; expected_arbitrary_type=User)\n```\n\nThis behavior can be changed via Model Config\n\nPydantic v1.x\n```python\nfrom pydantic_collections import BaseCollectionModel\n...\nclass UserCollection(BaseCollectionModel[User]):\n    class Config:\n        validate_assignment_strict = False\n```\n\nPydantic v2.x\n```python\nfrom pydantic_collections import BaseCollectionModel, CollectionModelConfig\n...\nclass UserCollection(BaseCollectionModel[User]):\n    model_config = CollectionModelConfig(validate_assignment_strict=False)\n```\n\n```python\nusers = UserCollection()\nusers.append({'id': 1, 'name': 'Bender', 'birth_date': '2010-04-01T12:59:59'})  # OK\nassert users[0].__class__ is User\nassert users[0].id == 1\n```\n\n#### Using as a model field\n\n`BaseCollectionModel` is a subclass of `BaseModel`, so you can use it as a model field\n```python\n...\nclass UserContainer(BaseModel):\n    users: UserCollection = []\n        \ndata = {\n    'users': [\n        {'id': 1, 'name': 'Bender', 'birth_date': '2010-04-01T12:59:59'},\n        {'id': 2, 'name': 'Balaganov', 'birth_date': '2020-04-01T12:59:59'},\n    ]\n}\n\ncontainer = UserContainer(**data)\ncontainer.users.append(User(...))\n...\n```\n",
    "bugtrack_url": null,
    "license": "Apache 2",
    "summary": "Collections of pydantic models",
    "version": "0.6.0",
    "project_urls": {
        "Homepage": "https://github.com/romis2012/pydantic-collections"
    },
    "split_keywords": [
        "python",
        "pydantic",
        "validation",
        "parsing",
        "serialization",
        "models"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "baabf9956f44b42eb6d66b0a542b842cd3f824637b872c549f04a3c9fd6463c3",
                "md5": "bde5083e6983ea8842042c50af380941",
                "sha256": "ec559722abf6a0f80e6f00b3d28f0f39c0ed5feb1641166230eb75e9da880162"
            },
            "downloads": -1,
            "filename": "pydantic_collections-0.6.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "bde5083e6983ea8842042c50af380941",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 11403,
            "upload_time": "2024-07-09T10:43:21",
            "upload_time_iso_8601": "2024-07-09T10:43:21.389083Z",
            "url": "https://files.pythonhosted.org/packages/ba/ab/f9956f44b42eb6d66b0a542b842cd3f824637b872c549f04a3c9fd6463c3/pydantic_collections-0.6.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "68b3ca1ba73ce72fc36b950bcc8d499a7085c8709f0a1a17f1e977bcd1ed5e88",
                "md5": "3b371424d881a972f052d0254aa43983",
                "sha256": "c34d3fd1df5600b315cdecdd8e74eacd4c8c607b7e3f2c9392b2a15850a4ef9e"
            },
            "downloads": -1,
            "filename": "pydantic_collections-0.6.0.tar.gz",
            "has_sig": false,
            "md5_digest": "3b371424d881a972f052d0254aa43983",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 11199,
            "upload_time": "2024-07-09T10:43:24",
            "upload_time_iso_8601": "2024-07-09T10:43:24.510350Z",
            "url": "https://files.pythonhosted.org/packages/68/b3/ca1ba73ce72fc36b950bcc8d499a7085c8709f0a1a17f1e977bcd1ed5e88/pydantic_collections-0.6.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-07-09 10:43:24",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "romis2012",
    "github_project": "pydantic-collections",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "pydantic-collections"
}
        
Elapsed time: 0.58728s