Every service with a typed core eventually hits the same wall: the objects you trust inside the process are not the objects the network hands you. A payload arrives as JSON, your code wants an attrs class, and somebody has to translate โ field by field, with validation, forever. Hand-rolled converters start as ten innocent lines of dict-wrangling and end as a module nobody dares touch, because every new field means another manual check in another place, and the mapping between your types and your wire format quietly rots.
The second tax arrives at 3 a.m., when the payload is wrong. If your deserializer raises a bare KeyError from somewhere deep inside nested collections, you learn almost nothing: which field failed, in which object, against which expected type? Libraries that only half-support typed data force you to choose between fast-but-cryptic errors and slow-but-readable ones โ and both choices hurt at scale.
cattrs, the serialization layer of the attrs ecosystem, takes a different route. Rather than interpreting your classes at runtime forever, it writes specialized un/structuring functions for them, keeps a dispatch layer that routes every type to the right hook, and layers strategies and preconfigured converters on top for the hard cases: unions, inheritance, non-JSON types. The repository is small enough to read in an afternoon, and it is dense with engineering ideas worth stealing for your own hot paths. This post walks the real tree of the main branch, and every claim below was verified against the actual sources.
The overview view: the public API fronts two converters; dispatch routes types to hooks; the codegen package writes specialized functions; strategies and preconf converters extend both.
Reading the overview from left to right, these are the anchors worth opening first โ each link drops you at a verified line in main:
global_converter, L46 โ the module-level converter that the flatunstructure/structureAPI delegates to, with the comment recommending your own instance.Converter, L1101 โ the class that generates a specialized hook per attrs class instead of walking fields at runtime.unstructure(), L359 โ dispatches on the objectโs class;structure()at L631 dispatches on the target type.MultiStrategyDispatch, L89 โ exact-match, singledispatch and predicate rules combined under one LRU-cached entry point, wrapped at L118.make_dict_structure_fn, L761 โ the factory that emits a dedicated structuring function for one class.already_generating, L19 โ a thread-local that guards codegen against self-referencing class graphs, raisingRecursionErrorfrom gen/init.py L313.configure_tagged_union, L23 โ tags union members with a_typekey in the payload, default defined at L27.transform_error, L56 โ flattens validation exception groups into readable messages with paths.ClassValidationError, L95 โ the validation error type, built on anExceptionGroupbase declared at L28.
The detail view: converter methods, dispatch internals, the gen factories, the three strategies, the preconf family and the error stack, each node linked to its source file.
Two Converters, One Contract
The library ships two converters with the same surface. BaseConverter (declared at converters.py L188) builds two dispatch stacks in its constructor โ one for unstructuring at L243, one for structuring at L290 โ and populates them with predicate rules for mappings, sequences, sets, tuples, unions, enums, sentinels and attrs classes. Its attrs handling is the slow path: unstructure_attrs_asdict at L666 walks fields and dispatches per value, and structure_attrs_fromdict at L818 does the reverse, field by field, on every call.
Converter (L1101) keeps the contract but replaces the attrs handlers with generated ones: at L1210 it registers gen_unstructure_attrs_fromdict and at L1213 gen_structure_attrs_fromdict for generic-aware attrs classes. Its __slots__ at L1104 read like a feature list โ omit_if_default, forbid_extra_keys, type_overrides, use_alias, _unstruct_collection_overrides โ and each knob is ultimately consumed by the codegen package. The general rule: BaseConverter pays dispatch cost on every call, Converter pays it once per class. One relic survives for old imports: the historical name GenConverter is now a type alias for Converter, declared on the last line of the module at L1536, and exported from __all__ at L124.
Dispatch: Three Strategies and an LRU Cache
MultiStrategyDispatch (dispatch.py L89) is the traffic controller. Its docstring says it plainly: a combination of exact-match dispatch, functools.singledispatch, and predicate-based FunctionDispatch. Lookup order lives in dispatch_without_caching at L120: try singledispatch first, then the direct dictionary of exact registrations, then the predicate rules, and finally the fallback factory. The whole thing is wrapped in lru_cache(maxsize=None) at L118, so repeated calls on the same type resolve to a dict hit.
FunctionDispatch (L31) is the interesting half: register() inserts new rules at index 0 (L58), so the most recently registered predicate wins, and dispatch walks the list in order, swallowing predicate exceptions along the way. The fallbacks come from fns.py: identity at L14 is the default unstructure fallback, and raise_error at L19 explodes with a StructureHandlerNotFoundError for unknown structure targets โ the default wired in at converters.py L210. Converter copying is a first-class operation as well: both classes expose copy() (for BaseConverter at converters.py L1060, for Converter at L1475), and each constructor records how many predicate rules were built-in via _unstruct_copy_skip and _struct_copy_skip at L356, so a copy can transplant only the user-added rules through MultiStrategyDispatch.copy_to (dispatch.py L189).
The Codegen: Where the Hooks Come From
The gen package is where performance comes from. make_dict_structure_fn (L761) takes a class and synthesizes a structuring function for it, honoring converter-level defaults like _cattrs_forbid_extra_keys at L764 and _cattrs_detailed_validation at L769. Its unstructure twin, make_dict_unstructure_fn, sits at L259. Two details stand out. First, the recursion guard: generation state lives in a thread-local already_generating (gen/_consts.py L19), and if the same class re-enters while it is being processed, the factory raises RecursionError at L313 so recursive class graphs resolve lazily instead of looping forever. Second, debuggability: generated functions get synthetic filenames through generate_unique_filename (gen/_lc.py L6) โ names like <cattrs generated ...> โ with real source lines stuffed into linecache, so a traceback into a generated hook shows readable code.
Field-level customization flows through override() (gen/init.py L54) into the frozen AttributeOverride at gen/_consts.py L10: omit_if_default, rename, omit, struct_hook, unstruct_hook. Generic classes are handled by substituting type variables via deep_copy_with (_generics.py L10), and collections get their own factories โ mapping_structure_factory at L1081 and iterable_unstructure_factory at L1209. Because generated code is source-level Python, it stays compatible with the usual typing toolchain โ the project even type-checks in CI with mypy per its pyproject configuration.
From Slow Paths to Specialized Code: Build Facts
The numbers behind the design are worth recording. The core converters.py runs 1,536 lines and the codegen module 1,241 โ the two halves of the slow-path/fast-path split โ while dispatch.py does its job in 193 lines. Versioning is calendar-based: HISTORY.md records the 26.2.1 release dated 2026-09-26, with an unreleased NEXT section above it. The support floor is Python 3.10 per pyproject.toml, and the error design leans on ExceptionGroup (declared at errors.py L28), with the exceptiongroup backport carried as a dependency for older interpreters.
The benchmark suite in bench/ makes the slow-versus-fast story measurable: six files, driven by pytest and pytest-benchmark, where test_attrs_primitives.py defines a 30-field attrs class and hammers both converters under the AS_DICT and AS_TUPLE strategies. The test suite is property-based at heart โ hypothesis is a pinned dev dependency โ across 67 files under tests/, which is why round-trip guarantees hold for the weird cases too; our hypothesis walkthrough covers that style of testing. Even the legacy src/cattr package stays in lockstep: its gen.py re-exports make_dict_structure_fn, make_dict_unstructure_fn, the hetero-tuple and mapping factories, and override from cattrs.gen, so vintage imports resolve to the same code.
The preconf package ships ten ready-made converter modules โ bson, cbor2, json, msgpack, msgspec, orjson, pyyaml, tomlkit, tomllib and ujson โ each patching the types its format cannot express natively. The stdlib JSON one is representative: JsonConverter (preconf/json.py L23) adds dumps/loads on top of Converter, encodes bytes as base85 strings at L52, serializes datetimes as ISO 8601 strings at L56, and registers sets and counters to collapse into lists and dicts. Shared helpers live in preconf/__init__.py: is_primitive_enum at L45 lets string and int enums pass through untouched, and unstructure_datetime_as_timestamp at L18 treats naive datetimes as UTC so both ends of a round-trip agree.
Strategies and Preconf: The Hard Cases
Unions are the classic failure mode for any serializer, and cattrs attacks them from two angles. configure_tagged_union (strategies/_unions.py L23) writes a _type discriminator into each unstructured payload and routes structuring through a tag-to-hook mapping; the strategy even has distinct closures depending on whether the converter forbids extra keys, visible at L70. include_subclasses (strategies/_subclasses.py L44) takes the opposite approach for inheritance: it folds an entire class tree into one hook, optionally delegating to the union strategy through _include_subclasses_with_union_strategy at L171. Both rest on a small compatibility helper, subclasses() (subclasses.py L11), which filters duplicate subclass reports from slotted dataclasses and attrs classes on newer Pythons. For codebases that already own their serialization, use_class_methods (strategies/_class_methods.py L11) registers hook factories that inspect the arity of your _serialize-style methods โ one or two parameters, checked at L38 โ and wire them in as hooks.
Honest Limits
The two-converter split is powerful but is also two behavior profiles to learn: defaults like Enjoyed this post? Never miss out on future posts by following us omit_if_default only apply to the generating converter, and mixing them in one codebase invites subtle drift. The dispatch cache is per instance and is cleared on every hook registration (dispatch.py L144 and L181), so patterns that re-register hooks at runtime repeatedly pay generation and cache costs. The tagged-union strategy only supports the dict un/structuring strategy, as its own docstring states at L45 โ tuple-mode serialization is out of scope there. Detailed validation trades raw speed for exception-group richness, and transform_error is an extra API surface to learn before the errors become the asset they are designed to be. And the legacy cattr namespace is now a thin facade โ it imports global_converter from cattrs at cattr/init.py L16 โ so new code should import from cattrs directly. None of these are deal-breakers; they are the edges you should know before the 3 a.m. payload arrives.