cattrs: Flexible Object Serialization and Validation#

Because validation belongs to the edges.


cattrs is a Swiss Army knife for (un)structuring and validating data in Python. In practice, that means it converts unstructured dictionaries into proper classes and back, while validating their contents.

cattrs works best with attrs classes, and dataclasses where simple (un-)structuring works out of the box, even for nested data, without polluting your data model with serialization details:

>>> from attrs import define
>>> from cattrs import structure, unstructure
>>> @define
... class C:
...     a: int
...     b: list[str]
>>> instance = structure({'a': 1, 'b': ['x', 'y']}, C)
>>> instance
C(a=1, b=['x', 'y'])
>>> unstructure(instance)
{'a': 1, 'b': ['x', 'y']}

However, cattrs does much more with a focus on functional composition and not coupling your data model to its serialization and validation rules.

To learn more on why to use cattrs, have a look at Why cattrs?, and if you’re convinced jump right into The Basics!