03
The three-way split: dissolve, survive, disambiguate
One shipping model whose tests show which classic patterns Python dissolves, which remain design, and which share a name with something else.
One shipping model witnesses the three-way split of the classic patterns. Each test asserts the mechanism named in its title, not only a value.
Dissolve
A language feature does the work:
- Strategy is a callable: a function, a lambda or a
functools.partialfills thePricingRuleslot ofquote. - Factory Method is a class stored in a dict.
- Iterator is a generator;
pagesreads aTrackingHistoryone page at a time. - Template Method is a function that takes hooks.
- Builder is a keyword-only dataclass, and Prototype is
dataclasses.replace. - Visitor is
functools.singledispatch, with noacceptmethod on the events. - Null Object is an optional, and
mypy --strictrejects the unguarded call with[union-attr]. - Value Object is a frozen dataclass (
Money), and Registry is__init_subclass__.
Survive
A deferred call is a functools.partial in a collections.deque. Undo is different: it
needs a command object that remembers what it replaced, and Amendment is that object.
Disambiguate
- The Decorator pattern wraps an instance at runtime (
SurchargearoundBaseRate). The@audited(sink)syntax rebinds a function name at definition time. The tests show the two are independent. - A module is the Singleton:
tariff_tablebuildsTARIFFonce, and a separate log records the single load. functools.cached_propertygives lazy initialisation without a proxy, andCarrierGatewayProxyforwards only the attributes it doesn’t define.- A
Protocolis structural, while an abstract base class is nominal.
Build, run, observe
From the repository root, once:
uv sync --locked --all-packages
Then change into the example directory:
cd examples/03-three-way-split
uv run pytest -v
uv run mypy --strict src tests
The example README lists what each test verifies.