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 cattrsVerified import paths — ran on the pinned version, not inferred.
Demonstrates basic structuring of a dictionary into an `attrs` class instance and unstructuring it back, using the global converter.
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))`).
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))`).
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.
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.
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.
Install `typing_extensions` using pip: `pip install typing_extensions`.
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))`.
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.
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.
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.
No dependency data recorded yet.