Skip to main content

Composable complex class support for attrs and dataclasses.

Project description

cattrs: Flexible Object Serialization and Validation

Because validation belongs to the edges.

Documentation License: MIT PyPI Supported Python Versions Downloads Coverage


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.

Example

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']}

Have a look at Why cattrs? for more examples!

Features

Recursive Unstructuring

  • attrs classes and dataclasses are converted into dictionaries in a way similar to attrs.asdict(), or into tuples in a way similar to attrs.astuple().
  • Enumeration instances are converted to their values.
  • Other types are let through without conversion. This includes types such as integers, dictionaries, lists and instances of non-attrs classes.
  • Custom converters for any type can be registered using register_unstructure_hook.

Recursive Structuring

Converts unstructured data into structured data, recursively, according to your specification given as a type. The following types are supported:

  • typing.Optional[T] and its 3.10+ form, T | None.
  • list[T], typing.List[T], typing.MutableSequence[T], typing.Sequence[T] convert to lists.
  • tuple and typing.Tuple (both variants, tuple[T, ...] and tuple[X, Y, Z]).
  • set[T], typing.MutableSet[T], and typing.Set[T] convert to sets.
  • frozenset[T], and typing.FrozenSet[T] convert to frozensets.
  • dict[K, V], typing.Dict[K, V], typing.MutableMapping[K, V], and typing.Mapping[K, V] convert to dictionaries.
  • typing.TypedDict, both ordinary and generic.
  • typing.NewType
  • PEP 695 type aliases on 3.12+
  • attrs classes with simple attributes and the usual __init__[^simple].
  • All attrs classes and dataclasses with the usual __init__, if their complex attributes have type metadata.
  • Unions of supported attrs classes, given that all of the classes have a unique field.
  • Unions of anything, if you provide a disambiguation function for it.
  • Custom converters for any type can be registered using register_structure_hook.

[^simple]: Simple attributes are attributes that can be assigned unstructured data, like numbers, strings, and collections of unstructured data.

Batteries Included

cattrs comes with pre-configured converters for a number of serialization libraries, including JSON (standard library, orjson, UltraJSON), msgpack, cbor2, bson, PyYAML, tomlkit and msgspec (supports only JSON at this time).

For details, see the cattrs.preconf package.

Design Decisions

cattrs is based on a few fundamental design decisions:

  • Un/structuring rules are separate from the models. This allows models to have a one-to-many relationship with un/structuring rules, and to create un/structuring rules for models which you do not own and you cannot change. (cattrs can be configured to use un/structuring rules from models using the use_class_methods strategy.)
  • Invent as little as possible; reuse existing ordinary Python instead. For example, cattrs did not have a custom exception type to group exceptions until the sanctioned Python exceptiongroups. A side-effect of this design decision is that, in a lot of cases, when you're solving cattrs problems you're actually learning Python instead of learning cattrs.
  • Resist the temptation to guess. If there are two ways of solving a problem, cattrs should refuse to guess and let the user configure it themselves.

A foolish consistency is the hobgoblin of little minds, so these decisions can and are sometimes broken, but they have proven to be a good foundation.

Credits

Major credits to Hynek Schlawack for creating attrs and its predecessor, characteristic.

cattrs is tested with Hypothesis, by David R. MacIver.

cattrs is benchmarked using perf and pytest-benchmark.

This package was created with Cookiecutter and the audreyr/cookiecutter-pypackage project template.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cattrs-26.1.0.tar.gz (495.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cattrs-26.1.0-py3-none-any.whl (73.1 kB view details)

Uploaded Python 3

File details

Details for the file cattrs-26.1.0.tar.gz.

File metadata

  • Download URL: cattrs-26.1.0.tar.gz
  • Upload date:
  • Size: 495.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for cattrs-26.1.0.tar.gz
Algorithm Hash digest
SHA256 fa239e0f0ec0715ba34852ce813986dfed1e12117e209b816ab87401271cdd40
MD5 0dfeb8a55487c3aa7ae27489b72f0c68
BLAKE2b-256 a0ecba18945e7d6e55a58364d9fb2e46049c1c2998b3d805f19b703f14e81057

See more details on using hashes here.

Provenance

The following attestation bundles were made for cattrs-26.1.0.tar.gz:

Publisher: pypi-package.yml on python-attrs/cattrs

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file cattrs-26.1.0-py3-none-any.whl.

File metadata

  • Download URL: cattrs-26.1.0-py3-none-any.whl
  • Upload date:
  • Size: 73.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for cattrs-26.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 d1e0804c42639494d469d08d4f26d6b9de9b8ab26b446db7b5f8c2e97f7c3096
MD5 1271958f77ed1ed183fdabc08f70a2a4
BLAKE2b-256 805660547f7801b97c67e97491dc3d9ade9fbccbd0325058fd3dfcb2f5d98d90

See more details on using hashes here.

Provenance

The following attestation bundles were made for cattrs-26.1.0-py3-none-any.whl:

Publisher: pypi-package.yml on python-attrs/cattrs

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page