Type hints are wonderful documentation, and mypy turns them into a genuine static safety net. But the moment data crosses a boundary you do not control — a JSON payload, a CSV row, a third-party SDK return value — every annotation downstream becomes a promise nobody checks. You discover a function quietly returned a list of None only when production crashes three layers away. Statically checked codebases still rot at their edges, because the type system stops exactly where your knowledge of the incoming data stops.
typeguard, maintained by Alex Grönholm in the agronholm/typeguard repository, attacks that gap at run time. What makes the library worth a source tour is not the idea of runtime checking — several projects share it — but the mechanism. Instead of wrapping your functions in proxy objects, @typechecked recompiles them, weaving checks directly into the function’s own bytecode, and an optional import hook applies the same transformation to entire packages at import time. There is no wrapper frame, just your function with a few extra statements inside.
This tour reads the actual tree of the default branch rather than the README. The package is compact: twelve modules under src/typeguard totalling 4,094 lines, dominated by two heavyweights — a 1,243-line AST transformer and a 1,303-line checker registry. Everything else orbits those files: a thin decorator layer, a meta-path import hook, a pytest plugin, and a small configuration and memo layer. Let’s walk from the decorator you type down to the checkers that raise the exception you see.
Overview of typeguard: the public API feeds two instrumentation routes — the decorator route that recompiles single targets and the import hook route that swaps module loaders — and both converge on the shared check functions, checker registry, memo and configuration.
Reading the overview from left to right, these are the anchors worth opening in the source; every link points at a verified line in the default branch:
- typechecked, L152 — the public decorator; it accepts a bare function or class, or keyword overrides and returns a partial until applied.
- instrument, L55 — the heart of the decorator route: reparse the module, transform it, recompile, and rebuild the function from the new code object.
- TypeguardTransformer, L481 — the AST visitor that strips the decorator and injects argument, return, yield and assignment checks.
- check_argument_types, L119 — the frame-based checker that validates every annotated argument of the calling function.
- origin_type_checkers, L1166 — the registry table mapping over fifty origin types such as
list,dictandUnionto checker callables. - install_import_hook, L216 — inserts a meta-path finder so modules imported afterwards are instrumented automatically.
- iterate_samples, L59 — the knob deciding whether large collections get every item checked or only the first.
- pytest_configure, L83 — where the pytest plugin reads its options and installs the import hook for a whole test run.
The detail graph expands those anchors into the functions that do the work — including the closure-rebuilding path most wrappers never face.
Detail view: the decorator path reparses and recompiles its target, the import hook path swaps the source loader, and both end in the same registry lookup and checker dispatch that raises TypeCheckError.
From a Decorator Call to Recompiled Bytecode
When you stack @typechecked on a function, the decorator first refuses easy cases: functions without a code object or module, functions defined in a REPL (their code filename is <stdin>), and anything already wrapped with a __wrapped__ attribute beyond the supported classmethod, staticmethod and property trio. Each refusal becomes an InstrumentationWarning and the untouched original is returned — decoration never breaks your code, it just does less.
The real work in instrument() starts by taking the module source with inspect.getsource, parsing it, and visiting it with a TypeguardTransformer told which qualified name to look for. Crucially the transformer walks the whole module, not just the target, because names used in annotations must resolve correctly. The module is recompiled with compile(), and find_target_function() recursively descends the new code object’s co_consts to recover the recompiled target by matching its qualified-name path and original line number.
The subtle part is the closure. Injected checks may reference names that only appeared in annotations, so the recompiled function can have different free variables than the original. When co_freevars differ, typeguard builds fresh closure cells for those names — including ForwardRef placeholders for values it cannot resolve — and reuses the original cells otherwise. Then it assembles a new function via FunctionType, copying __name__, __qualname__, defaults, and newer attributes like __type_params__ on 3.12. Under python -O, the decorator checks __debug__ and returns the target untouched — a deliberate escape hatch for production.
From Whole Modules to Instrumented Imports
Decorating hundreds of functions by hand does not scale, so the import hook route exists. install_import_hook() scans sys.meta_path for the standard PathFinder — raising a clear RuntimeError if none exists — and inserts a TypeguardFinder at position zero. Its should_instrument() applies an ignore list first, then package prefix matching; passing None means every module imported from now on gets instrumented.
When a module matches, the finder swaps the spec’s loader for a TypeguardLoader whose source_to_code() decodes the source, parses it, runs a fresh transformer over the whole tree, fixes AST locations, and compiles. Its exec_module() patches cache_from_source so instrumented bytecode lands in a cache directory tagged typeguard plus the version triple — your normal .pyc files are never clobbered.
Inside the transformer, function handling is where the library earns its keep. It deletes the @typechecked decorator itself so instrumentation cannot recurse, removes typing.overload stubs entirely, and skips functions marked with @typeguard_ignore — simply typing.no_type_check aliased at runtime, so static tools stay happy too. For each remaining annotated function it builds a dict literal mapping argument names to transformed annotation expressions and inserts one call to check_argument_types_internal as the first statement. If the body ends without an explicit return but the annotation is not None, it appends a checked return None. A GeneratorDetector finds yield expressions so a Generator[int, str, bool] annotation splits into yield, send and return checks, and an AnnotationTransformer normalizes annotations — substituting builtin generics like dict with their typing equivalents and erasing anything that collapses to Any, since checking against Any is a no-op worth skipping.
From One Annotation to a Tuned Checker Registry
At runtime the injected calls funnel into check_type_internal, which resolves a checker by walking a list of lookup functions. The built-in lookup is appended at import, and load_plugins() prepends anything registered under the typeguard.checker_lookup entry-point group — plugin autoload happens at import unless TYPEGUARD_DISABLE_PLUGIN_AUTOLOAD is set. The lookup falls back through the special cases static typing adds: TypedDict classes, tuple subclasses covering NamedTuple, protocols detected via _is_protocol, ParamSpec and TypeVar instances, PEP 695 aliases, NewType and sentinels. Everything else is a dict hit in origin_type_checkers, which maps over fifty origin types to concrete checkers for lists, mappings, sets, tuples, callables, I/O handles, patterns and literals.
Union checking shows the craftsmanship: check_union() tries each member in order, accepts the first that passes, and raises only when every member fails — embedding an indented, per-member breakdown of exactly why each alternative rejected the value. Errors accumulate path elements as they bubble up, so a failure reads like argument "items"[2].name rather than a bare assertion.
Checking has a price proportional to how much data it inspects, and typeguard makes the trade-off explicit. CollectionCheckStrategy offers FIRST_ITEM (the default) and ALL_ITEMS; iterate_samples() returns either a single-element list from next(iter(collection)) or the whole collection, and lists, dicts, sets and arbitrarily sized tuples all consult it. The TypeCheckConfiguration dataclass also carries a forward-reference policy (ERROR, WARN or IGNORE), a fail callback that can warn instead of raising, and a debug_instrumentation flag. One detail deserves attention: the public check_type() builds its own configuration per call rather than reading the global one, so an embedding application cannot reconfigure a library’s internal checks. Suppression is equally careful — suppress_type_checks() drives an integer counter guarded by a threading.Lock, so nested and concurrent suppressions behave predictably.
From One Test File to a Whole Suite Under Enforcement
The pytest plugin registers through the standard pytest11 entry point, so installing typeguard is enough for pytest to discover it. Its options include --typeguard-packages, an ignore list, debug instrumentation, a fail-callback reference like typeguard:warn_on_error, and the forward-ref and collection-strategy policies. pytest_configure() turns :all: into instrument-everything, warns loudly if a requested package is already imported — instrumentation cannot retroactively fix loaded modules — and installs the hook before tests collect. Combining this with pytest gives you type enforcement across every module your suite touches, and hypothesis pairs naturally: property-based tests generate inputs from your annotations while typeguard verifies outputs. If a legacy helper cannot survive checking, @typeguard_ignore opts it out; warn_on_error downgrades failures to warnings while you migrate.
From 4,094 Library Lines to 6,323 Test Lines
The engineering facts behind those numbers are worth stating plainly. The library is twelve modules: the checker registry at 1,303 lines and the transformer at 1,243 are the twins that matter, followed by check functions (364), the import hook (262), decorators (243), utilities (205), the pytest plugin (141), configuration (113), suppression (80), a 48-line memo, exceptions (42) and a 50-line re-export hub. The test suite is 6,323 lines across sixteen files — about 1.5 lines of test per line of library — and its shape mirrors the architecture: test_checkers.py at 2,134 lines and test_transformer.py at 2,009 dominate, with a 363-line dummymodule.py as fixture source for instrumentation tests.
Two smaller choices reveal the codebase’s ambitions. It declares requires-python >= 3.10 yet carries version-gated branches up to Python 3.15 imports like NoExtraItems and sentinel, plus 3.12-only PEP 695 alias handling. And the return-value checker recognizes all fifty names in BINARY_MAGIC_METHODS — a table the comments honestly describe as lifted from mypy’s shared parser — so rich comparison methods may return NotImplemented even where the annotation says bool.
Honest Limits
Runtime type checking is not static checking, and typeguard does not pretend otherwise. Under Enjoyed this post? Never miss out on future posts by following us python -O the decorator is a documented no-op, so optimized deployments silently lose every guarantee. The import hook only affects modules imported after installation — hence the plugin’s already-imported warnings — and REPL-defined functions or wrappers outside the supported trio are refused with a warning rather than mis-instrumented. The frame-based helpers lean on sys._getframe, which the comments admit is not officially supported on every Python implementation, and generator instrumentation deliberately excludes yield from delegation from yield checks. Finally, FIRST_ITEM sampling means a 10,000-element list usually has 9,999 unchecked items by default — flip to ALL_ITEMS when the data really matters and accept the cost. Used with those limits in mind — static analysis for structure, runtime checks at boundaries — typeguard closes the gap between what your annotations promise and what your data actually is.