Runnable companions to the book.
Every pattern chapter has an example behind it. Each example is a self-contained Python project in one uv workspace, with a pytest suite, pytest-mock where a collaborator needs substitution, and no containers. Read the matching chapter for context, then run the example from its directory with the same local uv and Python 3.15 toolchain the prerequisites chapter installs.
Runnable examples
Each example makes a single pattern or idiom concrete and runnable with one command. Every card links to the example's page on this site, which describes the example and its tests, and each page links to the source on GitHub. Each example also stands alone and builds without the book.
A frozen Consignment that proves the toolchain
A frozen, slotted Consignment built from validated ConsignmentId and Weight value types and amended with dataclasses.replace. It passes ruff, mypy --strict and pytest, so a green run means the environment is ready for every other example.
Patterns sorted into dissolve, survive and disambiguate
A shipping model where each test proves one claim: Strategy as a callable, Iterator as a generator, Visitor as singledispatch, Null Object checked by mypy, Command with undo, and the Decorator pattern kept apart from the @ syntax.
Separate reasons to change, a tax rule as data, and a contract suite
A rate quote split into pricing, tax and audit, extended with a new tax rule as data, and checked by a contract suite that catches the substitution failures mypy can't see.
Small Protocols owned by consumers and one plain wiring function
Booking and tracking each depend on the smallest Protocol they use, carrier adapters satisfy them without naming them, and one plain function wires the whole application.
Special methods the interpreter calls on the type
Cartons that hash equal when turned, money that multiplies from either side and refuses to mix currencies, and a history that is sized and iterable, checked at runtime and under mypy.
Value types from one dataclass declaration
Weight, Money and SlotId as frozen slotted dataclasses, an amendment that is a new value, a stowage plan that stays an entity, and the checks mypy makes and misses.
Interfaces as shapes, absence as a type
A carrier lookup that returns an optional gateway, a Protocol beside an ABC, a callback Protocol, inferred variance, and the checks runtime_checkable does and doesn't make.
Release on every path, committed on success
A manifest writer with __enter__ and __exit__, the generator form and why it needs try, an ExitStack that unwinds in reverse, and what mypy reads from __exit__'s return type.
A test is evidence for one named claim
A rating engine that books only the cheapest carrier, tested with a checked fake, Mock, Mock(spec=) and create_autospec, an injected clock, a restored environment and mypy over the tests.
Strategies as callables in a registry
A read-only registry of pricing callables, a partial and a frozen rule object, a quote that records the rule key, and a class-per-strategy fixture that passes the same table.
Fixed steps, hooks and a final template
A customs skeleton that no hook can reorder, required and defaulted hooks, and an abstract declarer for destinations that share a schedule, both forms giving the same declaration.
A lifecycle in a table and in a match
Booked to delivered as a read-only frozendict and as frozen states under assert_never, one behaviour table for both forms, and a transit-delay model that is reproducible because its generator is injected.
Amendments as values with undo
Reweigh, redirect and set instructions as frozen values under a closed union, an apply that returns the inverse computed at run time, and a queue that applies a batch all or nothing.
A registry of constructors and a kit per carrier
Self classmethods in a Callable slot as the factory method, a GoF creator hierarchy kept as a comparison, and a generic frozen kit whose reference type ties the gateway to the label printer.
A keyword-only request, and templates copied with replace
A frozen dataclass names every argument and validates once, a positional constructor and a fluent builder run the same table as comparisons, and replace and copy.replace copy a template and rerun its checks.
A module, a lazy import and a load that runs once
The tariff table is a module attribute, loaded on first use with a lazy import, and a lock with a double check keeps a run-time load to one. Borg, a metaclass and a new-based form run the same table as comparisons.
One adapter, one facade call, two booking kinds
A client whose shape already matches needs no adapter, and Fastline's SDK gets one that converts pounds and errors in a single place. A class adapter, a class per kind and carrier, and a branching caller run the same tables as comparisons.
Two things called Decorator, and a proxy
Layers stack while the program runs and compare by value; the @ form rebinds a name once. An explicit caching proxy is checked by mypy, and a forwarding proxy runs the same table as a comparison.
One question for a group and a leaf, one object per commodity
A closed union of consignment and consolidation, matched where the kinds differ. A weak pool shares one frozen commodity per code, and the GoF component classes and a cache run the same tables as comparisons.
Who is told, in what order, and for how long
A typed signal delivers to a snapshot in subscription order, gathers failures into one ExceptionGroup and queues nested events. Bound methods are held weakly, and a plain list runs the same table as a comparison.
Who decides, in what order, and when to release
Stages return a decision or None to pass it on, the first decision wins, and the final stage is typed so it cannot pass. A mediator holds the release rule and its state, and a choreography shows what it replaces.
One pass or many, how much to read, who closes
A generator replaces the cursor class. The history walks many times, pages read one batch at a time, and a reader closes its file when it is closed or collected, not when a loop over a named reader breaks.
Closed or open, what to capture, and a grammar with two readings
Each operation over the event union is one match that mypy checks for every kind. A rollback restores a frozen snapshot and leaves the audit alone, and one tariff tree is both priced and explained.
Identity, signatures, factories, stacking and registries
The order of a stack decides what a cache hides from a timer. functools.wraps keeps a renderer's identity for runtime tools, ParamSpec keeps its signature for mypy, and a class decorator belongs above a slotted dataclass.
Validators, lookup order and cached values
A copied setter drifts, a descriptor does not. One Positive class validates every weight and extent, a cached_property computes a chargeable weight once, and slots=True removes the validator without a word.
Fallbacks, registration and what mypy cannot see
One generic function replaces the visitor class. A raising fallback names the unregistered kind, and a registration made in another module exists only once that module is imported.
Class keywords, refusals and imports
A carrier registers by a class keyword, and a bad class is refused before it reaches the registry. The metaclass form passes the same table and can conflict with other metaclasses.
Lazy loading without a surrogate
A tracking history loads its fields on the first read and keeps them as plain attributes. A __getattr__ that reads a missing attribute recurses under copy, and an allow-list stops it.
Tables, totality and asking forgiveness
A table of callables replaces an if-chain, and mypy checks every entry but not that every kind has one. A cache read in one lookup survives an eviction that breaks check-then-read.
Measuring structure against the function
One rating function and a factory, strategy and visitor quote the same table. mypy and ruff pass both, so the structure is counted with ast and call counts.
Patching where the name is looked up
A rating engine written before anyone tested it. Patch it where its names are looked up, see which patches miss, and see what mypy checks at each one.
One table, every step
A rating engine written before anyone tested it. Pin what it does, change its structure one step at a time, and run the same table after each step.
Intent rows and golden quotes
Five rows written from the requirement pass a tidy-up that changes totals. Quotes recorded from the legacy engine list the rows it changed.
Parity table and strangler-style router
A first draft of the rewrite quotes 5, 20 and 50 kg differently from the legacy engine. A parity table lists every row where the two engines differ, and a router serves one zone at a time.
Slot reservation and rating pools
Two threads parked between reading and writing take the same slot on either CPython build. A lock that covers the read gives each its own, and a benchmark script holds every timing.
Feeds, quotes, signals and queues
An await between reading and writing lets five tasks take one slot. A feed closes through aclosing, quotes run in a task group, an async signal runs every subscriber, and a command queue shuts down without a sentinel.
One booking, seven areas
A booking that customs holds releases its slot and cancels the carrier booking in reverse order. The tracking event waits for the commit, and one function chooses the concrete parts.
Three drafts, three gates
Three drafts written for the book fail different sets of gates: types and lint, the pattern shape rules and a behaviour oracle. A recorded fake stands in for the model client, and no test uses the network.
pytest run inside pytest
Each row of the reference names its witness, and most are tests on the pinned pytest. Strictness options, import modes and command-line options run in an inner session, and the test asserts the outcome counts or the exit status.
A fake first, an autospec next, a patch last
Each API row of the reference is a test on the pinned pytest-mock. Autospecs, call records, patches, spies and stubs run against one carrier gateway, and two static tests show what mypy sees.
Ask the shipment
One remittance line, read by a reader that asks the shipment and by a comparison reader that reaches through to the invoice. They agree until a credit is granted, and then only the reader that asks the shipment reports the amount due.
Building every example
Clone the repo and run every example in one pass with the pinned
local toolchain (uv and Python 3.15; see the prerequisites chapter and
scripts/check-prereqs.sh).
git clone https://github.com/patterncatalyst/design-patterns-with-python.git
cd design-patterns-with-python
uv sync --locked --all-packages
./scripts/verify.sh
After the one-time uv sync --locked --all-packages at the
root, every example also runs from its own directory with
uv run pytest.