cattrs: Composable Attrs/Dataclass Structuring
cattrs is a Python library (version 26.1.0) that provides composable tools for converting between unstructured Python data (like dictionaries) and structured data (like `attrs` classes and `dataclasses`). It excels at recursively structuring and unstructuring data while supporting type hints and offering extensive customization via hooks. Releases are frequent, often including breaking changes across minor versions.
Warnings
- breaking As of v25.3.0, abstract sets (`collections.abc.Set`) are now structured into `frozenset` by default, instead of `set`. This might affect code expecting mutable sets.
- breaking As of v25.2.0, sequences (`collections.abc.Sequence`) are now structured into `tuple` by default, instead of `list`. This change provides better immutability and consistency.
- breaking As of v25.1.0, `StructureHandlerNotFoundError` is raised more eagerly (on hook creation rather than on first use). This helps surface missing hooks sooner.
- breaking As of v24.1.0, unstructuring hooks for `typing.Any` now consistently use the runtime type of the value. Previously, this behavior was underspecified and inconsistent.
- gotcha The top-level `cattrs.structure()` and `cattrs.unstructure()` functions operate on a global converter instance. Registering hooks or changing settings on this global converter can lead to unexpected side effects across different parts of an application or in library code.
Install
-
pip install cattrs
Imports
- structure
from cattrs import structure
- unstructure
from cattrs import unstructure
- Converter
from cattrs import Converter
Quickstart
from attrs import define
from cattrs import structure, unstructure
@define
class User:
id: int
name: str
email: str
# Unstructured data (e.g., from JSON)
unstructured_data = {"id": 1, "name": "Alice", "email": "alice@example.com"}
# Structure into a User instance
user_instance = structure(unstructured_data, User)
print(f"Structured: {user_instance}")
# Unstructure back to a dictionary
unstructured_output = unstructure(user_instance)
print(f"Unstructured: {unstructured_output}")