Every Python codebase has one: the function annotated as taking list[int] that, at 2 a.m., receives a list of strings parsed out of a JSON payload. The static checker saw a clean call site and approved it. The runtime never checked anything, because CPython discards annotations at call time. The bug surfaces three layers away from the actual mistake, in a stack trace that points at code nobody touched. It is widely recognized that annotation-only type hints are documentation, not enforcement — and documentation does not throw TypeError when the wrong data arrives.

beartype attacks exactly that gap, and it does so with an unusual engineering constraint: type checks must add effectively zero overhead. Instead of walking your objects with interpreted isinstance trees on every call, beartype generates a dedicated Python wrapper function per decorated callable — source code emitted as a string, compiled, and exec’d — where each annotated parameter becomes a plain boolean expression. The result runs in constant time, which is why teams use it in hot paths, data-ingestion boundaries, and test suites running under pytest, where runtime failures are the whole point of the exercise.

What makes the project worth a source tour is how much machinery hides behind that one-line decorator. The public surface is tiny — essentially @beartype, BeartypeConf, and BeartypeStrategy — but underneath sits a reduction layer that normalizes fifteen years of Python typing PEPs into one canonical shape, a breadth-first code generator, and several layers of caching. Reading this code is a masterclass in making a dynamic language behave, briefly, like a compiled one.

beartype architecture overview from public decorator to generated check code

The beartype decoration walk: the package re-export funnels into the decorator core, wrapper assembly, and the BFS code generator that emits per-hint boolean checks.

Reading the overview from left to right:

  • beartype, L247 — the package root re-exports the private decorator from beartype._decor.decormain, keeping the entire implementation invisible to downstream importers while __all__ publishes only eight public names.
  • decormain, L62 — the first fork in the road: if the interpreter was launched optimized (python -O), the entire decorator reduces to an identity function, honoring the convention that optimizations disable runtime checking.
  • beartype, L73 — the “real” decorator, which validates the configuration with die_unless_conf and serves two modes: decorate an object immediately, or return a cached decorator bound to a configuration.
  • beartype_object, L39 — the dispatcher that splits classes from plain callables, and fatal decoration from a warning-coercing variant used by import hooks that must never crash a host application.
  • make_func_check, L37 — the assembly step that concatenates a synthesized signature, per-parameter check code, and the return check into one wrapper source string.
  • make_check_expr, L172 — the code factory its own docstring calls “the beating heart of beartype”: a breadth-first search over the graph of nested type hints, emitting one boolean subexpression per reachable node.
  • _HINT_CONF_TO_CHECK_EXPR, L1593 — the memoization dictionary mapping each (HintSane, BeartypeConf) pair to already-generated code, so identical hints never pay for code generation twice.
  • die_if_unbearable, L66 — the beartype.door runtime-introspection API, alongside is_bearable and is_subhint, for checking ad-hoc values without decorating anything.
  • O1, L79 — the default strategy in BeartypeStrategy: constant-time checking that inspects a single randomly selected item of each container, with Ologn and On declared but not yet implemented.
beartype detail graph showing decorator core, wrapper assembly, codegen, reducers and cave types

The detailed view: wrapper assembly fans out into raiser factories, the BFS codegen core, per-PEP hint reducers, and the cave-type aliases that model CPython's stranger objects.

The decorator that disappears under -O

The entry module is structured as a fork. At import time, beartype._decor.decormain asks whether the interpreter is optimized and, if so, binds the name beartype to a hand-written identity decorator that returns its argument untouched. Only in the standard runtime state does it import the actual implementation from beartype._decor.decorcache. The file even carries the comment “This is where @beartype REALLY lives” above that import. This design keeps the decorator’s signature identical in both worlds — the docstring is attached to whichever implementation survives — while respecting the -O contract that asserts are stripped and runtime checks should be free to disappear.

Configuration mode is equally frugal. Calling @beartype(conf=...) with no object returns a private closure that applies that configuration to whatever it decorates next; those closures are stored in the _bear_conf_to_decor dictionary at the bottom of decorcache.py, so repeated configuration calls reuse one closure. The configuration object itself, BeartypeConf, is a frozen dataclass in beartype/_conf/, and its validity is re-checked on every decoration through die_unless_conf.

From annotation to executable boolean

Follow the call chain for a plain function and the architecture becomes mechanical. beartype_object in decorcore.py routes non-classes to beartype_nontype, which builds a BeartypeCallDecorFuncData metadata object aggregating everything the generator needs: the function’s signature, annotations, scope, and name. Then make_func_check in the _wrap subpackage produces the wrapper body from two pieces — code_check_args for parameters and code_check_return for the return value.

Each piece funnels into beartype/_check/make/checkmakefunc.py, whose factories call make_check_expr for every annotated parameter. That call returns a 2-tuple: a boolean code snippet plus a scope dictionary of hidden parameters the wrapper will need. The snippet contains a placeholder for the parameter name, which the caller string-replaces before splicing the snippet into the wrapper body. Finally the assembled source goes through make_func in beartype._util.func.utilfuncmake, which compiles and execs it, yielding a real Python function that wraps the original and raises a descriptive violation on the first bad argument. Nothing about the check is interpreted per-item at runtime beyond what the generated code literally says.

From hint graph to one-liner: what the codegen actually builds

The generator is best understood through its own comments. The make_check_expr docstring describes a breadth-first search over “the abstract graph of nested type hints reachable from the subscripted arguments of the passed root type hint”. A hint like dict[str, list[tuple[int, str]]] becomes nested membership tests, each guarding a child extraction, all combined into a single boolean expression. Union hints (Optional[X], X | Y) reduce through dedicated reducers; Literal["a", "b"] comparisons come from the PEP 586 module; protocol classes come from PEP 544 reducers. A _redmap.py dispatch table maps each detected hint sign to its reducer, and the result is wrapped in a HintSane record — the normalized hint snapshot that both codegen and the error formatter consume.

Three engineering choices stand out. First, memoization: the generated snippet is cached under the (HintSane, BeartypeConf) key, so the second function annotated with the same hint in the same configuration skips generation entirely. Second, probabilistic sampling: the default O(1) strategy checks exactly one randomly selected item per container, which is why the code templates thread a random integer — see the CODE_GET_VIOLATION_RANDOM_INT snippet in beartype/_data/check/code/func/datacodefunccheck.py — into generated loops. Third, resilience: since PEP 810-style lazy imports can defer module initialization in future interpreters, the package root installs a lazy-import filter guard at beartype/__init__.py, line 84, protecting a small set of hostile submodules before any other import runs.

The same pragmatism shows up in beartype/_cave/. That package catalogs CPython objects that have no dedicated type you can name portably: AnyType = object, callable frame and traceback aliases, weakref proxies, generator and coroutine C types. When an annotation or a violation message needs to reference “the type of a module object” or “a traceback object”, it reaches for these aliases instead of hand-rolling isinstance chains. This is the sort of unglamorous layer that keeps a runtime checker honest across interpreter versions, and it pairs naturally with property-based testing under hypothesis, where generated edge-case values routinely land in exactly those corners.

The public neighborhoods: door, vale, claw, bite

Beyond the decorator, the repo ships four small public subpackages, each a distinct API over the same machinery. beartype.door is the introspection API: is_bearable(obj, hint) returns a boolean, die_if_unbearable raises a violation with a human-readable message, and TypeHint wraps any hint in a class hierarchy with __contains__-style semantics. beartype.vale exposes composable validators — Is[lambda value: ...] and attribute-level checks — implemented as an indexable factory class whose __getitem__ builds validator instances at beartype/vale/_is/_valeis.py, line 265; those validators integrate with Annotated[...] so the codegen treats them as ordinary leaves.

beartype.claw is the boldest piece: import hooks (beartype_all, beartype_this_package, beartype_package, beartype_packages) that decorate entire packages at import time. That is why decorcore.py contains the warning-coercing decoration path — a package-wide hook cannot afford to crash on one untypeable callable, so failures downgrade to warnings and decoration continues. Finally, the newer beartype.bite subpackage — the Beartype Inferential Type-hint Engine — flips the problem around: given an arbitrary object, infer_hint reverse-engineers a PEP-compliant hint that describes it. The tour detail graph stops at the checker itself, but these four subpackages show the same codegen core being reused in four very different postures: decorate, introspect, hook, and infer.

Static tooling still matters, of course — a runtime checker complements, rather than replaces, what mypy proves about call sites before anything executes. The two disagree in instructive ways: static analysis trusts your annotations; beartype verifies the data that actually flows through them.

Honest Limits

The decorator is upfront about its boundaries, mostly in its own docstring. It supports pure-Python callables and classes; C-based callables such as builtins and C extensions are rejected with a BeartypeDecorWrappeeException. Decorated functions may not declare parameters prefixed with the reserved substring __beartype_, since generated wrappers hide their plumbing under that prefix. Under python -O, all checking silently vanishes — by design, but worth remembering if you ship optimized builds and rely on violations firing.

The strategy story has documented gaps: BeartypeStrategy declares four members, but Ologn and On are explicitly marked unimplemented pending a future release. Only O1 — one random item per container — and O0 (a deliberate no-op for blacklisting callables) exist. The practical consequence is that deep container contents are checked probabilistically, not exhaustively; a pathological payload could hide a bad item beyond the first sample. Generated wrappers also rely on reserved-name scoping and string-replaced placeholders rather than AST rewriting, which keeps generation fast but means the generated source, not an AST, is the unit of correctness. None of these caveats undermine the core trick: beartype’s source shows that the cheapest type checker is one your interpreter compiles once and never thinks about again.

Watch PyShine on YouTube

Contents