cattrs: Composable Attrs/Dataclass Structuring

26.1.0 · active · verified Sat Mar 28

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

Install

Imports

Quickstart

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}")

view raw JSON →