pydantic-collections


Namepydantic-collections JSON
Version 0.5.4 PyPI version JSON
download
home_pagehttps://github.com/romis2012/pydantic-collections
SummaryCollections of pydantic models
upload_time2024-02-25 08:59:05
maintainer
docs_urlNone
authorRoman Snegirev
requires_python
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": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "python pydantic validation parsing serialization models",
    "author": "Roman Snegirev",
    "author_email": "snegiryev@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/69/63/e233ec9f98380f68019dc9309f865ea256b7ebf54e8151166eb6467f52fd/pydantic-collections-0.5.4.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.5.4",
    "project_urls": {
        "Homepage": "https://github.com/romis2012/pydantic-collections"
    },
    "split_keywords": [
        "python",
        "pydantic",
        "validation",
        "parsing",
        "serialization",
        "models"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "51323336c4266594d7fb7aa599fbd63432ec2352d373983b6493333675eac026",
                "md5": "c129f000f194a56bebfea94ee46e28a0",
                "sha256": "5d107170c89fb17de229f5e8c4b4355af27594444fd0f93086048ccafa69238b"
            },
            "downloads": -1,
            "filename": "pydantic_collections-0.5.4-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c129f000f194a56bebfea94ee46e28a0",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": null,
            "size": 11450,
            "upload_time": "2024-02-25T08:59:03",
            "upload_time_iso_8601": "2024-02-25T08:59:03.260281Z",
            "url": "https://files.pythonhosted.org/packages/51/32/3336c4266594d7fb7aa599fbd63432ec2352d373983b6493333675eac026/pydantic_collections-0.5.4-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6963e233ec9f98380f68019dc9309f865ea256b7ebf54e8151166eb6467f52fd",
                "md5": "90417cd0c626e79805dc93cfb660140e",
                "sha256": "5bce65519456b4829f918c2456d58aac3620a866603461a702aafffe08845966"
            },
            "downloads": -1,
            "filename": "pydantic-collections-0.5.4.tar.gz",
            "has_sig": false,
            "md5_digest": "90417cd0c626e79805dc93cfb660140e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 11230,
            "upload_time": "2024-02-25T08:59:05",
            "upload_time_iso_8601": "2024-02-25T08:59:05.031641Z",
            "url": "https://files.pythonhosted.org/packages/69/63/e233ec9f98380f68019dc9309f865ea256b7ebf54e8151166eb6467f52fd/pydantic-collections-0.5.4.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-25 08:59:05",
    "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.19576s