Chapters

The whole book, in order.

Fourteen parts and the appendices, read in order the first time through. Each chapter also stands on its own for a reader jumping in to solve one problem. Pick a part, or start at the top.

Part 0 Orientation

The toolchain every example runs on (uv, ruff, mypy, pytest) and the consignment example that proves it works.

  1. Prerequisites and the toolchainThe Python 3.15, uv, ruff, mypy and pytest toolchain on Fedora, and a consignment example that checks it works.

Part 1 Why This Is Not a GoF Retelling

Patterns as decisions under forces, and the claim that several 1994 catalogue entries are now Python language features rather than designs you write.

  1. Patterns as decisions under forcesA design pattern records a decision made under competing forces, and its Consequences are the ledger. The rate quote shows how the dominant force picks the shape.
  2. What 1994 assumed, and what Python dissolvesThe assumptions the 1994 pattern catalogue was written under, and the Python features (callables, generators, protocols, modules, optional types) that remove the scaffolding while the underlying force often remains.

Part 2 Why Python Is Different

The map that sorts every catalogue pattern into those a language feature dissolves, those that remain design, and those whose name means two things in Python, followed by naming patterns so that teams and AI assistants read the same contract.

  1. The three-way split: dissolve, survive, disambiguateTwo questions sort every catalogue pattern into dissolves, survives or needs disambiguating, shown on one runnable shipping example.
  2. Naming patterns for teams and AI assistantsHow to name pattern roles and Python mechanisms so reviewers and AI assistants can check a diff against the contract the name promises.

Part 3 Principles: SOLID

The five SOLID principles in Python: single responsibility, open/closed and Liskov substitution, then interface segregation and dependency inversion without a framework.

  1. SRP, OCP, and LSP in PythonSingle responsibility, open-closed and Liskov substitution on one rate quote: three collaborators, a tax rule that arrives as data, and a contract suite for what mypy cannot see.
  2. ISP, DIP, and dependency injection without a frameworkA consumer names the smallest Protocol it uses, policy owns that abstraction, and one plain function wires the adapters, shown on a runnable booking service.

Part 4 The Python Substrate

The data model and dunder methods, dataclasses and value semantics, Protocol and structural typing with mypy, context managers, and proving a design works with pytest, pytest-mock, and mypy.

  1. The data model: dunder methods as the substrateOperators, builtins and f-strings are calls on the type, shown on shipping values whose equality, arithmetic, ordering, containers and text each fail somewhere distant when a method is missing or wrong.
  2. Dataclasses and value semanticsOne frozen, slotted dataclass declaration writes the structure of the Value Object pattern, and three decisions stay with the author: the invariant, immutable field types, and value or entity.
  3. Protocol, duck typing, and structural typing with mypyAn interface in Python is a shape the checker compares where a value is used, absence is a member of that shape's type so Null Object dissolves into an optional return, and Protocol and ABC are two mechanisms behind one word.
  4. Context managers: deterministic cleanupThe with statement runs __exit__ on every path out of a block, which removes the boilerplate of Resource Acquisition; what release means, whether an exception propagates and the order across resources stay with the author.
  5. Proving it works: pytest, pytest-mock, and mypyA test is evidence for one named claim, and it counts once it has been seen to fail. Fixtures supply dependencies by name, a mock checks less than a fake, create_autospec checks call shapes, and mypy checks the tests too.

Part 5 Selecting and Varying Behaviour

Strategy as a callable, Template Method and its function alternative, State and finite state machines, and Command with undo and command queues.

  1. Strategy: the callableStrategy's force survives while its structure dissolves into a callable type, a read-only mapping and a call, which leaves selection, configuration and what a quote records about the rule that priced it.
  2. Template Method and the function alternativeTemplate Method straddles: the hook structure dissolves into a function that takes hooks, and the inheritance form survives where a family of variants shares state and code across steps.
  3. State and finite state machinesState survives because no feature says which transitions are legal; a read-only table, frozen states with a match ending in assert_never, and a seeded transit model make the lifecycle short and checkable.
  4. Command, undo, and command queuesCommand survives where undo needs data a deferred call never kept: frozen amendment values, an inverse computed when the amendment runs, undo and redo stacks and a queue that applies all or nothing.

Part 6 Creating Objects Under Control

Factory Method and Abstract Factory, Builder with dataclasses and Prototype, and Singleton as a module, a Borg, or a metaclass.

  1. Factory Method and Abstract FactoryFactory Method dissolves into a class or a Self classmethod in a Callable slot, while Abstract Factory survives as one frozen kit per carrier family, with mypy tying only the products that pass values to each other.
  2. Builder, dataclasses, and PrototypeBuilder and Prototype dissolve into a frozen keyword-only dataclass that validates once and replace for copies, with the field types deciding what a shallow copy shares.
  3. Singleton: module, Borg, and metaclassSingleton needs disambiguating: the default is a module built at import time or on first use, with a parameter for tests and a double-checked lock for loads that need run-time input.

Part 7 Composing and Adapting Structure

Adapter, Facade, and Bridge; the Decorator pattern told apart from the @decorator syntax, with Proxy; and Composite with Flyweight.

  1. Adapter, Facade, and BridgeDuck typing removes an adapter only where shapes and units already agree; a facade is often a module function, and a bridge separates two axes of variation behind a narrow Protocol.
  2. Decorator the pattern vs @decorator the syntax, and ProxyThe Decorator pattern composes wrapper objects while the program runs, the @decorator syntax rebinds a name once at definition time, and a proxy keeps the interface to control access.
  3. Composite and FlyweightA consignment and a consolidation of consignments answer the same question through a closed union, and a flyweight pool shares one frozen commodity among them while deciding who builds it and how long it lives.

Part 8 Coordinating and Traversing

Observer, Mediator and Chain of Responsibility, Iterator through generators and the iterator protocol, and Visitor, Memento, and Interpreter.

  1. ObserverAn Observer is a callable, but the delivery contract is still a design: subscription order, failure isolation, events published during delivery, and how long a signal keeps a subscriber alive.
  2. Mediator and Chain of ResponsibilityA chain of responsibility is a tuple of callables, but the order of its stages and the final stage are still choices you make. A mediator keeps the rule for releasing a declaration, once its duty and inspection reports have arrived, in one place.
  3. Iterator: generators and the iterator protocolA generator replaces the cursor class, but one pass or many, how much to read and who closes the source are decisions the language leaves to you.
  4. Visitor, Memento, and InterpreterVisitor dissolves into a match over a closed union, while a snapshot and a tariff tree stay design: what to capture, what mustn't roll back, and the readings of one grammar.

Part 9 Idiomatic Python

Decorators done right, descriptors and properties, singledispatch, metaclasses and __init_subclass__, and dynamic attributes with __getattr__.

  1. Decorators done rightThe @ syntax is given, but getting a decorator right isn't: what wraps copies, what ParamSpec keeps for mypy, bare use of a factory, stacking order and class decorators.
  2. Descriptors and propertiesOne validator, written once, guarding every field that needs it, and when a plain property or a cached one is the better tool.
  3. singledispatch: the Visitor the language gives youDispatch on the type of the first argument without a visitor class, and the choices that matter once registrations can live in other modules.
  4. Metaclasses, __init_subclass__, and registriesRegister subclasses by a class keyword, refuse a bad class when it is defined, and see what only a metaclass can still do.
  5. Dynamic attributes: __getattr__ and Proxy as a featureAn object that loads its own fields on first access, and how to keep __getattr__ out of recursion and consistent with dir, copy and mypy.

Part 10 Patterns in the Wild

The shortcuts Python offers in place of full patterns (dict dispatch, function tables, EAFP) and the anti-patterns that come from misusing the catalogue.

  1. Shortcut patterns: dict dispatch, function tables, and EAFPReplace an if-chain with a table of callables, and read fields and shared state with one try instead of a check and a read.
  2. Anti-patterns and pattern misuseA pattern kept after its forces have gone is an anti-pattern. Price the same consignments with a function and with a class for every role, and count what the structure costs.

Part 11 Changing Inherited Code

Seams in Python, dependency-breaking techniques, Fowler and Feathers contrasted and combined, and the decision between refactoring and rewriting.

  1. Seams in Python: monkeypatch, injection, and duck typingFind the places in code you didn't write where a test can swap a dependency without editing it, and learn where a patch has to land for the swap to take effect.
  2. Dependency-breaking techniques for modern PythonBreak a legacy engine's hard-wired carrier calls one small step at a time, and use a single table of expected quotes to show that no step changed what the code does.
  3. Fowler vs Feathers, contrasted and combinedSee what each book assumes before you touch code, record what an inherited engine really quotes, and refactor it in small steps while a table of those quotes tells you the moment a total moves.
  4. Refactor or rewriteDecide between reworking an inherited engine and replacing it from the forces in front of you, prove a rewrite matches the old quotes before it takes traffic, and route one zone at a time.

Part 12 Concurrency

Two chapters on the GIL and performance, and on how asyncio reshapes the patterns.

  1. The GIL and performanceWhat the global interpreter lock guarantees and what it leaves to your own lock, how to tell the default build from the free-threaded one, which pool suits CPU-bound rating, and why a benchmark stays out of the tests.
  2. asyncio and the patternsHow six patterns change when an await is a switch point: a feed closed through aclosing, a session that survives cancellation, quotes in a task group, an async Observer and a command queue that shuts down.

Part 13 Putting It Together

A final project that combines the patterns, and working with AI and LLM tools on pattern-heavy code.

  1. Final projectOne booking through all seven domain areas: an acceptance test written first, undo in reverse on an ExitStack, publishing after the commit and a single composition root.
  2. Working with AI and LLM toolsThree hand-written drafts of one pricing function, three gates (types and lint, shape rules, a behaviour oracle) and a model client behind a Protocol, tested with recorded replies.

Part 14 Appendices

Reference material: build and toolchain, pytest, mocking, xUnit test patterns, a pattern-to-force quick reference, and programming principles reviewed in code.

  1. Build and toolchain reference: uv, ruff, mypyReference for the uv, ruff and mypy commands, the one root configuration each tool reads, and the traps between them.
  2. pytest referenceReference for the pytest configuration, import mode, fixtures, parametrisation, exception assertions and command-line options the examples rely on, each with the pytest page that describes it.
  3. Mocking reference: unittest.mock and pytest-mockReference for the unittest.mock and pytest-mock names the examples use, in the order they're preferred, each with the call that shows it.
  4. xUnit test patterns (Meszaros)Gerard Meszaros's xUnit test patterns for fixtures, test doubles, verification and dependency injection, mapped onto pytest and pytest-mock, with the two places where pytest-mock's names mean something else.
  5. Pattern-to-force quick referenceFour tables that give, for each pattern developed, its bucket, its force and its when-not rule in the words of the chapter that develops it, with a link to that chapter.
  6. Programming principles reviewed in codeReference to the programming principles the code shows, with the chapter that states each one, what it measures and, where one was fetched, the page it comes from, plus a runnable example of the Law of Demeter.