


# modelity
Data parsing and validation library for Python.
## About
Modelity is a data parsing and validation library, written purely in Python,
and based on the idea that data parsing and validation should be separated from
each other, but being a part of single toolkit for ease of use.
In Modelity, **data parsing** is executed **automatically** once data model is
**instantiated or modified**, while model **validation** needs to be explicitly
called by the user. Thanks to this approach, models can be feed with data
progressively (f.e. in response to user’s input), while still being able to
validate at any time (f.e. in reaction to button click).
## Features
* Declare models using type annotations
* Uses slots, not descriptors, making reading from a model as fast as possible
* Clean separation between **data parsing** stage (executed when model is
  created or modified) and **model validation** stage (executed on demand)
* Clean differentiation between unset fields (via special `Unset` sentinel) and
  optional fields set to `None`
* Easily customizable via pre- and postprocessors (executed during data
  parsing), model-level validators, and field-level validators (both executed
  during model validation)
* Ability do access any field via **root model** (the one for each validation is
  executed) from any custom validator, allowing to implement complex
  cross-field validation logic
* Ability to add custom **validation context** for even more complex validation
  strategies (like having different validators when model is created, when
  model is updated or when model is fetched over the API).
* Use of predefined error codes instead of error messages for easier
  customization of error reporting if needed
* Ease of providing custom types simply by defining
  `__modelity_type_descriptor__` static method in user-defined type, or by
  using `type_descriptor_factory` hook for registering 3rd party types.
## Rationale
Why I have created this library?
First reason is that I didn’t find such clean separation in known data parsing
tools, and found myself needing such freedom in several projects - both
private, and commercial ones. Separation between parsing and validation steps
simplifies validators, as validators in models can assume that they are called
when model is successfully instantiated, with all fields parsed to their
allowed types, therefore they can access all model’s fields without any extra
checks.
Second reason is that I often found myself writing validation logic from the
scratch for various reasons, especially for large models with lots of
dependencies. Each time I had to validate some complex logic manually I was
asking myself, why don’t merge all these ideas and make a library that already
has these kind of helpers? For example, I sometimes needed to access parent
model when validating field that itself is another, nested model. With
Modelity, it is easy, as root model (the one that is validated) is
populated to all nested models' validators recursively.
Third reason is that I wanted to finish my over 10 years old, abandoned project
**Formify** (the name is already in use, so I have chosen new name for new
project) which I was developing in free time at the beginning of my
professional work as a Python developer. That project was originally made to
handle form parsing and validation to be used along with web framework.
Although the project was never finished, I’ve resurrected some ideas from it,
especially parsing and validation separation. You can still find source code on
my GitHub profile: https://github.com/mwiatrzyk.
And last but not least, I don’t intend to compete with any of the existing
alternatives — and there are plenty of them. I simply created this project for
fun and decided to release it once it became reasonably usable, hoping that
maybe someone else will find it helpful.😊
## Example
Here's a condensed example of how to use Modelity:
```python
import json
import datetime
import typing
from modelity.api import Model, ValidationError, ModelError, validate, dump, load
# 1. Define models
class Address(Model):
    address_line1: str
    address_line2: typing.Optional[str]
    city: str
    state_province: typing.Optional[str]
    postal_code: str
    country_code: str
class Person(Model):
    name: str
    second_name: typing.Optional[str]
    surname: str
    dob: datetime.date
    address: Address
# 2. Create instances (parsing runs automatically)
addr = Address(
    address_line1="221B Baker Street",
    address_line2=None,
    city="London",
    state_province=None,
    postal_code="NW1 6XE",
    country_code="GB"
)
person = Person(
    name="Sherlock",
    second_name=None,
    surname="Holmes",
    dob=datetime.date(1854, 1, 6),
    address=addr
)
#: 3. Validate instances (on demand)
try:
    validate(person)
except ValidationError as e:
    print("Model is not valid: ", e)
    raise
# 4. Dump to JSON-serializable dict
person_dict = dump(person)
person_json = json.dumps(person_dict)  # Dump to JSON; use any lib you like to do that
# 5. Parse from dict
person_dict = json.loads(person_json)
try:
    same_person = load(Person, person_dict)  # Parsing + validation made by helper
except ModelError as e:  # Base for: ValidationError, ParsingError
    print("Model parsing or validation failed: ", e)
    raise
# 6. Accessing fields (just like using normal dataclasses).
print(same_person.address.country_code)
```
## Documentation
Please visit project's ReadTheDocs site: https://modelity.readthedocs.io/en/latest/.
## Disclaimer
**Modelity** is an independent open-source project for the Python ecosystem. It
is not affiliated with, sponsored by, or endorsed by any company, organization,
or product of the same or similar name. Any similarity in names is purely
coincidental and does not imply any association.
## License
This project is released under the terms of the MIT license.
## Author
Maciej Wiatrzyk <maciej.wiatrzyk@gmail.com>
            
         
        Raw data
        
            {
    "_id": null,
    "home_page": "https://github.com/mwiatrzyk/modelity",
    "name": "modelity",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4,>=3.9",
    "maintainer_email": null,
    "keywords": "parsing, validation, modelling, parser, validator, model, library, toolkit",
    "author": "Maciej Wiatrzyk",
    "author_email": "maciej.wiatrzyk@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/6a/7c/512d8e3ac1f41bdc7286ff895cdfbaa876ebb581536fecbfe103b718766a/modelity-0.26.0.tar.gz",
    "platform": null,
    "description": "\n\n\n\n# modelity\n\nData parsing and validation library for Python.\n\n## About\n\nModelity is a data parsing and validation library, written purely in Python,\nand based on the idea that data parsing and validation should be separated from\neach other, but being a part of single toolkit for ease of use.\n\nIn Modelity, **data parsing** is executed **automatically** once data model is\n**instantiated or modified**, while model **validation** needs to be explicitly\ncalled by the user. Thanks to this approach, models can be feed with data\nprogressively (f.e. in response to user\u2019s input), while still being able to\nvalidate at any time (f.e. in reaction to button click).\n\n## Features\n\n* Declare models using type annotations\n* Uses slots, not descriptors, making reading from a model as fast as possible\n* Clean separation between **data parsing** stage (executed when model is\n  created or modified) and **model validation** stage (executed on demand)\n* Clean differentiation between unset fields (via special `Unset` sentinel) and\n  optional fields set to `None`\n* Easily customizable via pre- and postprocessors (executed during data\n  parsing), model-level validators, and field-level validators (both executed\n  during model validation)\n* Ability do access any field via **root model** (the one for each validation is\n  executed) from any custom validator, allowing to implement complex\n  cross-field validation logic\n* Ability to add custom **validation context** for even more complex validation\n  strategies (like having different validators when model is created, when\n  model is updated or when model is fetched over the API).\n* Use of predefined error codes instead of error messages for easier\n  customization of error reporting if needed\n* Ease of providing custom types simply by defining\n  `__modelity_type_descriptor__` static method in user-defined type, or by\n  using `type_descriptor_factory` hook for registering 3rd party types.\n\n## Rationale\n\nWhy I have created this library?\n\nFirst reason is that I didn\u2019t find such clean separation in known data parsing\ntools, and found myself needing such freedom in several projects - both\nprivate, and commercial ones. Separation between parsing and validation steps\nsimplifies validators, as validators in models can assume that they are called\nwhen model is successfully instantiated, with all fields parsed to their\nallowed types, therefore they can access all model\u2019s fields without any extra\nchecks.\n\nSecond reason is that I often found myself writing validation logic from the\nscratch for various reasons, especially for large models with lots of\ndependencies. Each time I had to validate some complex logic manually I was\nasking myself, why don\u2019t merge all these ideas and make a library that already\nhas these kind of helpers? For example, I sometimes needed to access parent\nmodel when validating field that itself is another, nested model. With\nModelity, it is easy, as root model (the one that is validated) is\npopulated to all nested models' validators recursively.\n\nThird reason is that I wanted to finish my over 10 years old, abandoned project\n**Formify** (the name is already in use, so I have chosen new name for new\nproject) which I was developing in free time at the beginning of my\nprofessional work as a Python developer. That project was originally made to\nhandle form parsing and validation to be used along with web framework.\nAlthough the project was never finished, I\u2019ve resurrected some ideas from it,\nespecially parsing and validation separation. You can still find source code on\nmy GitHub profile: https://github.com/mwiatrzyk.\n\nAnd last but not least, I don\u2019t intend to compete with any of the existing\nalternatives \u2014 and there are plenty of them. I simply created this project for\nfun and decided to release it once it became reasonably usable, hoping that\nmaybe someone else will find it helpful.\ud83d\ude0a\n\n## Example\n\nHere's a condensed example of how to use Modelity:\n\n```python\nimport json\nimport datetime\nimport typing\n\nfrom modelity.api import Model, ValidationError, ModelError, validate, dump, load\n\n# 1. Define models\n\nclass Address(Model):\n    address_line1: str\n    address_line2: typing.Optional[str]\n    city: str\n    state_province: typing.Optional[str]\n    postal_code: str\n    country_code: str\n\nclass Person(Model):\n    name: str\n    second_name: typing.Optional[str]\n    surname: str\n    dob: datetime.date\n    address: Address\n\n\n# 2. Create instances (parsing runs automatically)\n\naddr = Address(\n    address_line1=\"221B Baker Street\",\n    address_line2=None,\n    city=\"London\",\n    state_province=None,\n    postal_code=\"NW1 6XE\",\n    country_code=\"GB\"\n)\n\nperson = Person(\n    name=\"Sherlock\",\n    second_name=None,\n    surname=\"Holmes\",\n    dob=datetime.date(1854, 1, 6),\n    address=addr\n)\n\n#: 3. Validate instances (on demand)\n\ntry:\n    validate(person)\nexcept ValidationError as e:\n    print(\"Model is not valid: \", e)\n    raise\n\n# 4. Dump to JSON-serializable dict\n\nperson_dict = dump(person)\nperson_json = json.dumps(person_dict)  # Dump to JSON; use any lib you like to do that\n\n# 5. Parse from dict\n\nperson_dict = json.loads(person_json)\ntry:\n    same_person = load(Person, person_dict)  # Parsing + validation made by helper\nexcept ModelError as e:  # Base for: ValidationError, ParsingError\n    print(\"Model parsing or validation failed: \", e)\n    raise\n\n# 6. Accessing fields (just like using normal dataclasses).\n\nprint(same_person.address.country_code)\n```\n\n## Documentation\n\nPlease visit project's ReadTheDocs site: https://modelity.readthedocs.io/en/latest/.\n\n## Disclaimer\n\n**Modelity** is an independent open-source project for the Python ecosystem. It\nis not affiliated with, sponsored by, or endorsed by any company, organization,\nor product of the same or similar name. Any similarity in names is purely\ncoincidental and does not imply any association.\n\n## License\n\nThis project is released under the terms of the MIT license.\n\n## Author\n\nMaciej Wiatrzyk <maciej.wiatrzyk@gmail.com>\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Data parsing and validation library for Python",
    "version": "0.26.0",
    "project_urls": {
        "Homepage": "https://github.com/mwiatrzyk/modelity",
        "Repository": "https://github.com/mwiatrzyk/modelity"
    },
    "split_keywords": [
        "parsing",
        " validation",
        " modelling",
        " parser",
        " validator",
        " model",
        " library",
        " toolkit"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "8e3346b53ae9aee86831c8a23040d053b316d2fd100a03ea0d86fee08e6bc148",
                "md5": "2c98555673a23e54a116e10fa250669b",
                "sha256": "b14ac50d6c13a867b84d88734a0446c53b3d21507b62657559626ce445249a72"
            },
            "downloads": -1,
            "filename": "modelity-0.26.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2c98555673a23e54a116e10fa250669b",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4,>=3.9",
            "size": 39037,
            "upload_time": "2025-10-09T18:48:25",
            "upload_time_iso_8601": "2025-10-09T18:48:25.994115Z",
            "url": "https://files.pythonhosted.org/packages/8e/33/46b53ae9aee86831c8a23040d053b316d2fd100a03ea0d86fee08e6bc148/modelity-0.26.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "6a7c512d8e3ac1f41bdc7286ff895cdfbaa876ebb581536fecbfe103b718766a",
                "md5": "1143f1fa1a2598bacd6529a27f8d18bf",
                "sha256": "757b37ec8370a18a21971cd35ed94b82c21fb46a357adcb01575db7924e013c7"
            },
            "downloads": -1,
            "filename": "modelity-0.26.0.tar.gz",
            "has_sig": false,
            "md5_digest": "1143f1fa1a2598bacd6529a27f8d18bf",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4,>=3.9",
            "size": 31982,
            "upload_time": "2025-10-09T18:48:27",
            "upload_time_iso_8601": "2025-10-09T18:48:27.237974Z",
            "url": "https://files.pythonhosted.org/packages/6a/7c/512d8e3ac1f41bdc7286ff895cdfbaa876ebb581536fecbfe103b718766a/modelity-0.26.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-09 18:48:27",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "mwiatrzyk",
    "github_project": "modelity",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "circle": true,
    "lcname": "modelity"
}