Registry / serialization / cattrs

cattrs

JSON →
library26.1.0pypypi✓ verified 26d ago

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.

pip install cattrs
INSTALL
IMPORT
SIG · CATTRS
C
cattrs
serializationpythonv26.1.0
Install
1.9s avg
Import
123ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v26.1.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.126s · 19.5MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.9s · import 0.120s · 20MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

structure
from cattrs import structure
unstructure
from cattrs import unstructure
Converter
from cattrs import Converter

Demonstrates basic structuring of a dictionary into an `attrs` class instance and unstructuring it back, using the global converter.

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}")
Debug
Known issues
breakingAs 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.
fix
If the previous behavior (structuring into `set`) is required, register a custom structure hook for `collections.abc.Set` on your converter instance (e.g., `converter.register_structure_hook(Set, lambda d, t: set(d))`).
affects: >=25.3.0
breakingAs 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.
fix
If the previous behavior (structuring into `list`) is required, register a custom structure hook for `collections.abc.Sequence` on your converter instance (e.g., `converter.register_structure_hook(Sequence, lambda d, t: list(d))`).
affects: >=25.2.0
breakingAs of v25.1.0, `StructureHandlerNotFoundError` is raised more eagerly (on hook creation rather than on first use). This helps surface missing hooks sooner.
fix
Ensure all types intended for structuring have appropriate hooks registered *before* attempting to use the converter. Consult the `cattrs` migration guide for details on customizing `unstructure_hook_fallback_factory` if necessary.
affects: >=25.1.0
breakingAs 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.
fix
If your application relied on the previous inconsistent behavior for `typing.Any`, you may need to explicitly register custom `unstructure_hook`s for specific types or `typing.Any` to achieve the desired effect.
affects: >=24.1.0
gotchaThe 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.
fix
For complex applications or when developing libraries, it is strongly recommended to create and manage your own `cattrs.Converter()` instance(s) and register hooks on those private instances to avoid polluting the global state.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'typing_extensions'
`cattrs` sometimes conditionally imports `typing_extensions` for compatibility with older Python versions, but dependency resolution or specific `cattrs` versions can lead to this module being missing on systems where it's still needed.
fix
Install `typing_extensions` using pip: `pip install typing_extensions`.
cattrs.errors.StructureHandlerNotFoundError: Cannot find a structuring handler for <class 'your.CustomClass'>
`cattrs` does not automatically know how to convert unstructured data (like a dictionary) into instances of arbitrary custom classes or complex types (e.g., `datetime` or a non-`attrs`/`dataclass` class) without a registered structuring hook.
fix
Register a custom structuring hook for the specific type with the `cattrs` converter. For example, for a `datetime` object: `converter.register_structure_hook(datetime, lambda d, t: datetime.fromisoformat(d))`.
TypeError: Invalid first argument to `register()`. ForwardRef('MyClass') is not a class.
The `register_structure_hook` or `register_unstructure_hook` methods, which use `functools.singledispatch` internally, require an actual class type as their first argument, not a `ForwardRef` object.
fix
Ensure that all classes are fully defined before attempting to register hooks for them using `ForwardRef`s. If you must use `ForwardRef`s, resolve them to the actual class type using `typing.get_type_hints` or by passing the actual class directly after it's defined.
ValueError: 'some_string' is not a valid MyEnum
When structuring data into an `Enum` type, the input value does not match any of the defined members (by value or name) of the target `Enum` class.
fix
Provide an input value that exactly matches one of the `Enum` members' values or names. If custom mapping or case-insensitivity is needed, register a custom structuring hook for the `Enum` type.
cattrs.errors.ForbiddenExtraKeysError: While structuring <class 'your.MyClass'>, extra keys were found: {'unexpected_key'}
The `forbid_extra_keys=True` option is enabled on the `cattrs` converter or for the specific class being structured, and the input data contains keys that do not correspond to any attributes defined in the target class.
fix
Either remove the extra keys from your input data before structuring, or disable the `forbid_extra_keys` setting if these extra keys should be ignored. If the keys are legitimate, add them as attributes to your target class.
Upgrade
Version history
26.1.0latest on PyPI · released Feb 18, 2026
Audit
Dependencies

No dependency data recorded yet.

Agent activity
26 hits · last 30 days
node
24
OpenAI (training)
1
Resources
cattrs — pip install cattrs · libregistry