Every Python developer has written the same class a hundred times: an __init__ that assigns three arguments to self, a __repr__ that someone forgot to update, an __eq__ that compares the wrong fields, and a __hash__ that was silently broken the moment __eq__ appeared. It is a small tax on every script and service, and it compounds across a codebase until boilerplate outweighs logic. The attrs library exists to delete that tax, and it has become one of the most widely adopted packages in the Python ecosystem for exactly that reason.

What most users never see is what sits behind the tiny public surface. The package advertises two decorators and a helper, but its source tree contains a 3,400-line engine module that writes, compiles, and installs Python source code at class-creation time. It maintains a compatibility shim for PyPy and for Python 3.11 through 3.14, a lazy-import facade to keep import attr fast, and a modern API layer that re-thinks the defaults learned over a decade of field reports. Understanding how those pieces cooperate is genuinely useful when you need to debug a slotted class, explain why your validator did not run, or decide between attr.s and @define.

This post is a source tour of the repository at the default branch on GitHub, not a paraphrase of the docs. Every symbol, path, and line number below was checked against the real tree. We will walk the facade, the core machinery, the code generator, the hook modules, and the modern layer, and we will end with an honest look at where the design costs you something. If you prefer a visual map first, the two diagrams embedded below were built directly from the repository structure.

Overview architecture of the attrs library showing the public facade, core machinery, modern API and behavior modules

Overview of the attrs architecture: the two public namespaces sit on top of the core machinery in _make.py, the modern API in _next_gen.py, and the pluggable behavior modules for validation, conversion, and attribute setting.

Reading the overview from left to right:

  • attrs(), L1353 is the classic @attr.s decorator. It accepts roughly thirty keyword knobs and, when the class body has been scanned, hands the collected attributes to the builder below.
  • s = attributes = attrs, L34 shows how the package keeps three spellings of one decorator alive, with ib = attr = attrib on the next line doing the same for fields.
  • _ClassBuilder, L647 is the orchestrator. One builder instance per decorated class coordinates every generated dunder.
  • build_class(), L800 runs that coordination: patch the original class or create a slotted clone, then install repr, hash, equality, ordering, and initialization.
  • _attrs_to_init_script(), L2187 writes the actual text of your __init__, line by line, including default handling and keyword-only flags.
  • _CountingAttr, L2731 is the sentinel object an attr.ib() returns in the class body; it accumulates defaults, validators, and converters until the decorator harvests them.
  • make_class(), L3261 lets you build a class programmatically from a name and a dict of attributes, with no class body at all.
  • define(), L23 is the modern @define decorator that auto-detects annotated fields and turns on slots by default.
  • instance_of(), L114 is the most-used validator in the catalog; in_(), optional(), deep_iterable(), and a dozen more share the same module.

The detail graph goes one level deeper, into the individual builder steps and the support modules that most tours skip.

Detailed architecture of attrs showing _ClassBuilder steps, code generation, the modern define API and support modules

Detail view: each builder step, the code-generation helpers, the modern API layer, and the support modules, with the edges showing how a class body flows into compiled methods.

The Facade: Two Namespaces, One Import Path

The package ships two import roots. attr/ is the historical, maximally compatible namespace; attrs/ is the modern spelling that re-exports the curated API from attr and adds nothing new on its own. The file src/attrs/__init__.py is only a page long because it is almost entirely from attr import define, field, frozen, ... statements. The whole public surface of attr/__init__.py fits in 120 lines, and that smallness is deliberate: heavy submodules are not imported eagerly. Line 83 defines _LAZY_SUBMODULES = {"converters", "validators", "filters"}, and line 116 installs a module-level __getattr__ so that touching attr.validators for the first time triggers the import on demand. It is a neat trick that keeps import attr cheap even though the machinery behind it is enormous.

There is also a small easter egg hiding in plain sight. Line 36 of the facade reads dataclass = partial(attrs, auto_attribs=True) # happy Easter ;), predating the stdlib dataclasses module and its PEP 557 specification. The compatibility instinct goes further: src/attr/_compat.py is 127 lines of version gates, including a PYPY flag and constants from PY_3_11_PLUS up to PY_3_14_PLUS, plus annotation extraction that switches to the new annotationlib module on Python 3.14. The library still supports interpreters with __slots__-related quirks, and the shim keeps that knowledge in one file instead of sprinkling it across the codebase.

Inside the 3,400-Line Engine Room

src/attr/_make.py is the heart of the project: 3,462 lines in the current tree, by far the largest module. Its structure is a study in keeping one concern per section. The top of the file holds user-facing constructors (attrib() at line 104, the attrs() decorator at line 1353, make_class() at line 3261). The middle holds the analysis pass: _transform_attrs() at line 381 walks base classes via the MRO, applies any field_transformer hook, and separates real fields from leftovers. The bottom holds the finalized public data model: Attribute at line 2462, Factory at line 3084 for lazy defaults, and Converter at line 3142.

Two composer helpers live here too, and the code comments at lines 3364 and 3365 explain why: and_() for validators and pipe() for converters are needed inside the module itself, so they are defined in _make.py and imported into .validators and .converters afterwards. That is why pipe shows up at line 3404 of the engine module even though users import it from attr.converters. The builders in src/attr/setters.py (82 lines: pipe, frozen, validate, convert) and src/attr/filters.py (72 lines: include, exclude) stay small because they only supply behavior that the engine wires in.

From _CountingAttr to Compiled Bytecode

Here is the build sequence that turns a class body into a working class, and it is the part most worth reading in the source. When the interpreter evaluates a class body decorated with @attr.s, each attr.ib() assignment leaves behind a _CountingAttr sentinel. The decorator harvests them, _transform_attrs() normalizes and orders them, and then _ClassBuilder takes over at line 647. Its add_init() step calls _attrs_to_init_script(), which assembles the text of __init__ as a string: argument parsing, None sentinels for defaults, converter calls, validator calls.

That string is not merely exec’d. _compile_and_eval() at line 217 runs compile(script, filename, "exec") and evaluates the bytecode, and its sibling _linecache_and_compile() registers the generated source with the linecache module so tracebacks into generated methods show real, readable code instead of <unknown>. Equality is generated the same way: _add_eq() at line 1835 emits an and-chain comparison per field. That last detail is recent, by the way; the changelog notes that from version 24.1.0 instances are no longer compared as tuples of attributes but with one big and condition, which is faster and behaves correctly around values like math.nan that poison tuple comparisons.

Slots get special treatment. _create_slots_class() at line 859 does not mutate your class; it builds a brand-new one with __slots__, copies over existing methods, re-links properties, and patches __setattr__ so that the on_setattr hooks run. That is why mutating class state after decoration can surprise people, and it is also why slotted classes are both faster and stricter about adding attributes.

Hooks on Assignment: Validators, Converters, Setters

Validation is where attrs earns its category. src/attr/validators.py is 766 lines of factory functions, each returning a small callable that receives (instance, attribute, value). instance_of() at line 114 raises TypeError on the wrong type; in_() at line 260 checks membership; optional() at line 215 wraps another validator and passes None through. The catalog also includes deep_iterable(), deep_mapping(), comparison helpers like lt() and ge(), and a not_() combinator. Conversion mirrors this shape in src/attr/converters.py: optional() at line 19, default_if_none() at line 64, and a practical to_bool() that understands the strings "yes", "off", and "0" among others.

The interesting engineering question is when these hooks fire. The global switch lives in src/attr/_config.py, a 31-line module holding _run_validators = True with getter and setter accessors; validate() at line 2004 of the engine checks it before running anything. Under the modern @define API, hooks also fire on assignment through on_setattr, chained by the builders in setters.py (pipe at line 11, frozen at line 32). Under the classic attr.s, nothing runs on assignment unless you opt in with on_setattr=. The modern layer’s frozen alias makes the trade-off explicit: line 431 of _next_gen.py defines it as partial(define, frozen=True, on_setattr=None), so immutability comes with the assignment hooks switched off, and attempts at mutation raise FrozenInstanceError from src/attr/exceptions.py.

The project tests all of this aggressively. Its own suite runs on pytest, and the property-based layer is powered by Hypothesis; the shared strategies live in tests/strategies.py, which imports hypothesis.strategies at line 13, and hypothesis is a declared dev dependency in pyproject.toml. Typing is covered too: the repository ships .pyi stubs beside every module so tools like mypy can type-check the generated API without importing the machinery, and the dev extras include pytest-mypy-plugins for stub validation. That triple coverage is a large part of why the library is trusted in everything from small scripts to data platforms.

The Modern Layer: define, field, and Auto-Detection

src/attr/_next_gen.py is only 678 lines, but it changes the defaults in ways that matter. define() (line 23) wraps attrs() while flipping several switches: slots on, validators and converters running on assignment, auto_exc on for exception classes, and order off. It also tries auto_attribs=True first and falls back on UnannotatedAttributeError, which is why @define just works whether you annotate your fields or not. The field() factory at line 434 replaces attr.ib() and, importantly, avoids leaving a _CountingAttr object visible in the class body.

The alias pairs are compact: mutable = define at line 430 and the frozen partial at line 431. The module also carries inspect() at line 655, which returns the signatures the generator produced for __init__, __eq__, and friends, a genuine debugging aid when you need to see what your class actually grew.

Honest Limits

The design has real costs, and the source is candid about them. First, the engine module is a monolith: 3,462 lines means features interact inside one file, and the docstring for attrs() alone runs for hundreds of lines explaining the thirty knobs. Second, slotted classes rebuild your class, so patterns that rely on mutating the class after decoration, or on subclasses that add attributes without slots, behave differently. Third, the two-API situation is a permanent documentation tax: attr.s with attr.ib, @attrs, and @define all work, and the project itself describes some of the differences as surprising. Fourth, hooks run in a defined order but composition is manual: chaining validators or converters is up to you via and_() and pipe(), there is no declarative schema. None of these are defects so much as trade-offs, but they are the ones you feel in production, and reading the source makes each of them predictable rather than mysterious.

Watch PyShine on YouTube

Contents