Patterns#
Cross-cutting style guidance that does not belong to any one type, function, or class. The Zen of Python distils the language’s design ethos into a checklist; the anti-patterns table catalogues what looks right but bites later. Both apply across every section of this handbook.
For the patterns that did live here, follow the move:
Topic |
Now at |
|---|---|
Looping idioms |
|
Comprehensions |
|
Unpacking |
|
Default values (dict) |
|
Mutable-default trap |
|
Files / |
|
Pythonic conditions |
|
Function tools / closures / partial / cache |
|
Decorators (function, parametrised, stacked, class) |
|
GoF patterns (Singleton, Factory, Strategy, Observer, Adapter, Facade) |
|
Middleware (plain, WSGI / ASGI) |
Zen#
The Zen of Python (import this) is genuinely operational
guidance, not folklore.
Explicit is better than implicit. Pass dependencies in.
Flat is better than nested. Early
return, guard clauses.Errors should never pass silently. Don’t
except: pass.In the face of ambiguity, refuse the temptation to guess.
There should be one obvious way to do it. When the standard library has it, use it.
Anti-patterns#
The patterns that look right but bite later. Each row is the form, the reason it bites, and the fix.
Anti-pattern |
Why and fix |
|---|---|
Mutable default argument |
|
Bare |
Catches |
|
Silently eats errors. Log at minimum; re-raise from a wrapper that adds context. |
Monkey-patching at import time |
Side-effects on import surprise users and make tests
order-dependent. Patch explicitly with
|
|
Pollutes the namespace and breaks tooling. Import what you use. |
Singleton via global state |
Pretends to be encapsulated but is global state. A module-level cached value is more honest. |
Long argument lists |
Past 5–6 parameters, group with a |
Stringly-typed APIs |
|
Comparing with |
Works but reads as a junior tell. Use |
Catching and re-raising without context |
|
References#
Syntax for the syntactic surface these patterns build on.
Control flow for loop and conditional idioms.
Functions for decorator, comprehension, and closure idioms.
OOP for the GoF catalogue.
Frameworks for middleware.
Data Structures for the data structures patterns operate over.
Libraries for
functools,itertools, andcontextlib.Design Patterns: Elements of Reusable Object-Oriented Software — Gamma et al. (the GoF book; standard OOP-patterns catalog).
Python Cookbook — Beazley and Jones.
PEP 8, style guide.