The local build-and-test loop
The local build-and-test loop. One locked environment feeds lint, format, strict type checking and tests in order; a red step returns you to the source, and the prerequisites script gates the toolchain first.
Diagrams for the book, covering architecture and flow.
Click any diagram to open it fullscreen. Each is
also available as .excalidraw source; open it on
excalidraw.com
to edit.
The local build-and-test loop. One locked environment feeds lint, format, strict type checking and tests in order; a red step returns you to the source, and the prerequisites script gates the toolchain first.
The rate-quote decision under four forces. Carrier tariffs, commercial surcharges and destination tax change on separate schedules while every quote must stay reproducible; the chosen shape follows from which force dominates.
Assumptions behind the classic patterns, each paired with the Python feature that removes it: functions as objects, structural typing, generators, modules imported once, and absence checked by the type checker.
The three-way split. Two questions sort every catalogue pattern: does the name mean two things in Python, and does a language feature resolve the force without the pattern's structure? The answers place each pattern in dissolves, survives or needs disambiguating.
One pattern name, two readers. A reviewer and an AI assistant read the same name for the same contract; naming the Python mechanism as well, a callable type alias rather than a class hierarchy, keeps both readers on the idiomatic shape.
One quote, three responsibilities. Pricing sits behind the RateCalculator Protocol and hands its net to tax rules keyed by destination country; the finished quote goes to an audit callable. Each changes for its own reason, and one contract suite checks every calculator.
Dependency injection without a framework. The composition root builds one carrier adapter and passes it to each consumer, which names only the small Protocol it needs; the adapter satisfies both Protocols structurally and imports neither.
How Python evaluates factor times price. The left operand's type asks first and returns NotImplemented for a Money, so Money's reflected method answers. For a float factor that method declines too, and the expression raises TypeError.
One declaration, the Value Object's structure. A frozen, slotted, ordered dataclass writes the constructor, repr, equality, hash, ordering and the assignment guard for SlotId; the invariant, immutable field types and the value-or-entity choice stay with you.
Three checks behind one booking call. The optional return makes absence a branch to narrow, the CarrierGateway Protocol is compared where a gateway is passed, and the CarrierBase ABC is checked at construction.
Both ways out of a manifest write. After __enter__ opens path.partial, the body writes lines; __exit__ then replaces the partial with path on success, or unlinks it and lets the exception propagate.
How a claim becomes evidence. A claim gets a witness test named after it, a negative fixture shows the failure it rules out, the test is seen failing when its check is deleted, and only a fresh, scrubbed run is quoted.
One quote, three rules in a slot. The caller names a rule, the read-only RATE_RULES registry returns a callable, and quote records the name with the price, whether the rule is a function, a partial or a frozen dataclass.
One customs skeleton, two ways to vary it. declare_customs fixes the order and the invariant steps and takes hooks for the rest; CustomsDeclarer keeps the same skeleton final and lets a family of destinations share its schedule.
One consignment lifecycle, two ways to write it. A read-only table maps a status and an event to the next status; a match over frozen states does the same with per-state data, and any other pair is refused. An injected generator drives delays.
Amendments as values on two stacks. Queued amendments are applied first in, first out, all or nothing; each application returns a new frozen request and the inverse it computed, which undo and redo move between the two stacks.
Factories as values. A read-only registry maps a carrier code to one kit per family. The reference type ties the gateway to the label printer, while the rate source stays consistent only because the whole kit is chosen once.
Building and copying a booking request. A template is copied into a frozen keyword-only request whose checks rerun on every replace, and only an immutable field type keeps two copies from sharing one list.
Four ways to load the tariff table once, in the order to reach for them. A module, a lazy import and a parameter come first; the class forms beside them each cost something the tests measure.
One call, two axes, one translation. The facade picks a gateway and a booking kind; each kind works through the narrow gateway Protocol, which one client already satisfies and the other reaches through an adapter that converts units.
Two things called Decorator, and a proxy. Layers are chosen per consignment and stacked as a value while the program runs; the @ form rebinds a name once at definition; the proxy keeps the interface and controls access.
One weight question, one shared commodity. A consolidation answers weight as a consignment does, summing its parts through nested groups; consignments reach a single frozen commodity per code from a pool that lets go of commodities nobody holds.
What a signal decides. Each event reaches a snapshot of subscribers in order, nested events wait their turn, failures are gathered and raised afterwards, and bound methods are held weakly so abandoned subscribers can go.
A declaration passes along an ordered tuple of clearance stages; the first stage that decides ends the walk, and a clean one is released by the final stage. A separate mediator releases a declaration after the reports it is owed arrive.
A tracking history gives each loop a fresh iterator, so two walks both see every event. Pages are read one batch at a time, and closing a reader closes its file.
Each operation over the closed event union is one match, and mypy reports a kind it leaves out. A booking rolls back from a frozen snapshot that leaves the audit alone, and one tariff tree is both priced and explained.
The order of a stack decides whether a timer sees a cache hit. 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.
One Positive descriptor validates six fields in three classes. A lookup tries data descriptors, then the instance dictionary, then non-data descriptors, so a cached property is read from the dictionary after its first computation.
tariff_code picks the most specific registered class and falls back to a function that raises. A registration made in another module exists only after that module is imported, and a method dispatches on the argument after self.
Creating a carrier class runs any __set_name__ hooks and then __init_subclass__, which refuses a bad class and registers a concrete one in a read-only view. A metaclass can enforce the same rules, but it can conflict with another library's metaclass.
A read that ordinary lookup can't answer reaches __getattr__, which loads the declared fields once into the instance dictionary and refuses any other name. Later reads skip it, and a class that relies on forwarding fails iter() and len().
Issuing a document looks the kind up in a read-only table and calls the issuer outside the try. Reading a duty rate asks forgiveness, so an eviction by another thread reloads the rate instead of raising KeyError.
The same quote from one function and from a factory, strategy and visitor. They pass the same table and the same type check, but the engine spreads the fuel surcharge across five definitions where the function holds it in one.
A patch replaces a name where the engine looks it up. The legacy module holds its own name for the FASTLINE call, so patching the carrier's module misses it, and so does patching the margin constant after the class is defined.
Each step moves the enabling point from a patched name toward a parameter mypy checks, and one characterisation table runs at every step. Subclass and override passes it too, but a misspelt method reaches the real carrier.
The same two rounding refactors under two kinds of test. Rows written from the requirement pass both, while golden quotes recorded from the legacy engine list the rows each refactor changed.
A router serves migrated zones from the rewrite and the rest from the legacy engine, and can run the rewrite in shadow. A parity table holds the two to the same quotes, and a first draft with exclusive band limits fails it.
Two threads reserving a slot on one sailing. Parked between reading and writing, they take the same slot on either build; a lock that covers the read and the write gives each its own.
A carrier session closes its feed when its body ends, subscribers run under gather, quotes run in a task group and commands drain from a queue. An await is a point where another task can run, and cancellation still closes the feed.
One booking through the desk's steps. A completed step registers its undo on an exit stack, a held declaration unwinds them in reverse, and the tracking event is published after the commit.
A draft is checked by three gates: types and lint, the pattern shape rules and a behaviour oracle. The three drafts are reported by different gates, and the findings on a rejected reply go back in the next prompt.