Design patterns in Python
Design patterns are named, reusable answers to common design problems. Many classic patterns need whole class hierarchies in Java or C++; in Python, functions, modules and duck typing make most of them a few lines. Use a pattern when it removes a real problem, not to look “designed”.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| let the caller choose an algorithm | strategy: pass a function | sorted(rows, key=by_date), retry(fetch, backoff=expo) |
| choose an algorithm from config text | a dict of functions | COMPRESSORS["gzip"] |
| give a strategy settings | functools.partial or a callable object |
partial(expo, base=2) |
| build an object from a name | a factory over a registry dict | make_exporter("csv") |
| let classes add themselves to a registry | a registration decorator or __init_subclass__ |
@register("csv") |
| build an object in more than one way | an alternative constructor | Config.from_toml(path) |
| fix the steps of an algorithm, vary one step | template method + hook | run() calls self.handle(item) |
| react to events without editing the emitter | observer: a list of callbacks | bus.subscribe("order.paid", send_email) |
| chain processing steps | a pipeline of functions | for step in steps: x = step(x) |
| assemble a complex object step by step | a builder with chainable methods | Request().header(...).json(...).build() |
| make a foreign object fit your interface | an adapter | class S3Storage: def get(...) wraps boto3 |
| add behavior around a function | a Python decorator | @retry(times=3) |
| add behavior around an object | a wrapper object (decorator pattern) | CachedStorage(storage) |
| one shared object for the whole program | a module-level object | settings = Settings() in config.py |
| make code testable without network or files | dependency injection | def sync(*, client=None, now=datetime.now) |
| collect output in a test | inject list.append |
job(log=lines.append) |
| accept only what a function uses | a small Protocol |
class SupportsGet(Protocol): ... |
| undo or queue actions | command: functions or partial in a list |
queue.append(partial(send, user)) |
| dispatch on a value’s type | functools.singledispatch |
@to_json.register |
| decide whether a pattern is worth it | YAGNI, rule of three | wait for the second or third real need |
SOLID in one table
Section titled “SOLID in one table”| Principle | Rule | Smell | Pythonic fix |
|---|---|---|---|
| Single responsibility | one reason to change per unit | a class that reads files, computes and formats | split by job into functions or small classes |
| Open/closed | extend by adding code, not by editing it | an if/elif chain on a kind or a type |
a dict of functions, a registry, a function parameter |
| Liskov substitution | a subclass works wherever its parent works | an override that raises NotImplementedError, rejects valid input or changes the meaning |
keep the contract; compose instead of inheriting |
| Interface segregation | depend only on the methods you use | a fat base class; methods that only raise | several small Protocols |
| Dependency inversion | high-level code depends on abstractions, not on details | hard-coded paths, print(), clients built inside functions |
inject callables or objects; build them in main() |
| Term | Meaning | Goal | Test |
|---|---|---|---|
| coupling | how much one part depends on another’s details | low | can I change this part without editing that one? |
| cohesion | how closely a unit’s contents belong together | high | can I state this unit’s job in one sentence without “and”? |
Patterns at a glance
Section titled “Patterns at a glance”| Pattern | Problem it solves | Pythonic form | When not to use |
|---|---|---|---|
| Strategy | swap an algorithm | a function parameter | only one algorithm exists |
| Factory / registry | build objects by name, from config | a dict of classes + a function | the caller already knows the class: call it |
| Template method | fixed steps, one varying step | a base class whose method calls a hook | a function parameter (strategy) is enough |
| Observer | many listeners, one event | a list of callables | one listener: call it directly |
| Builder | assemble an object step by step, with checks | chainable methods that return self |
keyword arguments or a dataclass do it |
| Pipeline | apply steps in order | a list of functions; generators | two fixed steps: call them |
| Adapter | make a foreign API fit yours | a small wrapper class | you own both sides: change one |
| Decorator (pattern) | add behavior around an object | a wrapper with the same methods | a Python decorator on a function is enough |
| Singleton | one shared instance | a module-level object | it hides state that tests must reset; inject it |
| Dependency injection | swap real parts for fakes | parameters with defaults | the dependency never varies and is pure |
| Command | queue, log or undo actions | a function, a partial, a dataclass |
a direct call works |
Strategy
Section titled “Strategy”import mathfrom collections.abc import Callablefrom functools import partial
type Backoff = Callable[[int], float] # attempt number -> seconds to wait
def constant(attempt: int, delay: float = 1.0) -> float: return delay
def exponential(attempt: int, base: float = 2.0, cap: float = 30.0) -> float: return min(cap, base**attempt)
BACKOFFS: dict[str, Backoff] = {"constant": constant, "exponential": exponential}
def schedule(retries: int, backoff: Backoff) -> list[float]: # the context return [backoff(i) for i in range(retries)]
print(schedule(4, constant), schedule(4, BACKOFFS["exponential"]))print(schedule(4, partial(exponential, base=3, cap=10)), schedule(3, math.sqrt))[1.0, 1.0, 1.0, 1.0] [1.0, 2.0, 4.0, 8.0][1, 3, 9, 10] [0.0, 1.0, 1.4142135623730951]| Form | When |
|---|---|
| a function | no settings: key=len, backoff=constant |
partial or a closure |
settings fixed once |
a callable object (__call__) |
settings to show in a repr or change later, or state |
| a name in a dict | the choice comes from text: config, CLI, a form |
When not to use: one algorithm and no plan for a second. Write backoff=exponential() by mistake and you call it: a TypeError here, or a number instead of a function.
Factory and registry
Section titled “Factory and registry”from collections.abc import Callablefrom typing import Any
EXPORTERS: dict[str, type] = {}
def register(name: str) -> Callable[[type], type]: def decorator(cls: type) -> type: if name in EXPORTERS: raise ValueError(f"exporter {name!r} is already registered") EXPORTERS[name] = cls return cls # return the class unchanged
return decorator
def make_exporter(name: str, **options: Any) -> Any: # the factory try: cls = EXPORTERS[name] except KeyError: known = sorted(EXPORTERS) raise ValueError(f"unknown exporter {name!r}; choose from {known}") from None return cls(**options) # a fresh object on every call
@register("csv")class CsvExporter: def __init__(self, sep: str = ",") -> None: self.sep = sep
def export(self, rows: list[list[object]]) -> str: return "\n".join(self.sep.join(map(str, r)) for r in rows)
@register("tsv")class TsvExporter(CsvExporter): def __init__(self) -> None: super().__init__(sep="\t")
print(repr(make_exporter("tsv").export([["id", "total"], [1, 9.5]])))try: make_exporter("xml")except ValueError as err: print(err)'id\ttotal\n1\t9.5'unknown exporter 'xml'; choose from ['csv', 'tsv']- A class registers when its module is imported. Import every plugin module (for example in the package
__init__.py), or the name is “unknown”. - Register classes, not instances: an instance would be shared by every caller.
- Plugins from other packages: entry points in
pyproject.tomlandimportlib.metadata.entry_points(group="myapp.exporters").
When not to use: one product, or the caller always knows the class. Then CsvExporter() is the factory.
Template method
Section titled “Template method”from abc import ABC, abstractmethod
class Job(ABC): def run(self, items: list[str]) -> list[str]: # the template: fixed steps results = [] for item in items: if not item.strip(): # shared validation continue results.append(self.handle(item.strip())) # the hook return self.finish(results)
@abstractmethod def handle(self, item: str) -> str: ... # required hook
def finish(self, results: list[str]) -> list[str]: # optional hook: a default return results
class SlugJob(Job): def handle(self, item: str) -> str: return item.lower().replace(" ", "-")
def finish(self, results: list[str]) -> list[str]: return sorted(results)
print(SlugJob().run(["Hello World", " ", "About Us"]))['about-us', 'hello-world']Template methods you already use: unittest.TestCase (setUp, test, tearDown), threading.Thread.run, logging.Handler.emit, http.server.BaseHTTPRequestHandler.do_GET, Django class-based views, PyTorch nn.Module.forward.
When not to use: the only variation is one function. Pass it as a parameter (strategy) instead of making a class hierarchy. Never override the template itself (run) in a subclass: it loses the shared steps.
Observer
Section titled “Observer”from collections import defaultdictfrom collections.abc import Callable
type Handler = Callable[[dict[str, object]], None]
class EventBus: # the subject def __init__(self) -> None: self._handlers: defaultdict[str, list[Handler]] = defaultdict(list)
def subscribe(self, event: str, handler: Handler) -> None: self._handlers[event].append(handler)
def publish(self, event: str, payload: dict[str, object]) -> None: for handler in self._handlers[event]: # the subject knows nothing else handler(payload)
bus = EventBus()sent: list[str] = []bus.subscribe("order.paid", lambda p: sent.append(f"email {p['user']}"))bus.subscribe("order.paid", lambda p: sent.append(f"invoice {p['order_id']}"))bus.publish("order.paid", {"user": "ada", "order_id": "A-1"})bus.publish("order.refunded", {"user": "bob"}) # no subscribers: nothing happensprint(sent)['email ada', 'invoice A-1']| Form | When |
|---|---|
| a list of functions | one event: on_save=[log, notify] |
| a dict of event name → handlers | an event bus with several events |
a base class with empty on_* methods |
several events; each observer overrides only some (training callbacks) |
| a flag on the subject | an observer must change the flow (stop, skip) |
When not to use: a single listener (call it), or when the order and failures of handlers matter (a handler that raises stops the others; make that explicit).
Builder and pipeline
Section titled “Builder and pipeline”from typing import Selffrom urllib.parse import urlencode
class RequestBuilder: def __init__(self, url: str) -> None: self._url = url self._headers: dict[str, str] = {} self._params: dict[str, str] = {}
def header(self, name: str, value: str) -> Self: self._headers[name] = value return self # a fluent interface: calls chain
def param(self, name: str, value: object) -> Self: self._params[name] = str(value) return self
def build(self) -> dict[str, object]: if not self._url.startswith("https://"): # check once, at the end raise ValueError("only https URLs are allowed") query = urlencode(self._params) # escapes &, = and spaces url = f"{self._url}?{query}" if query else self._url return {"url": url, "headers": dict(self._headers)}
req = ( RequestBuilder("https://api.example.com/orders") .param("page", 2) .param("limit", 50) .header("Accept", "application/json") .build())print(req["url"], req["headers"])
steps = [str.strip, str.lower, lambda s: " ".join(s.split())] # a pipelinetext = " Wireless EARBUDS "for step in steps: text = step(text) # each output is the next inputprint(repr(text))https://api.example.com/orders?page=2&limit=50 {'Accept': 'application/json'}'wireless earbuds'| Choose | When |
|---|---|
| keyword arguments or a dataclass | all parts are known at the call site (most cases) |
| a builder | parts are added in a loop, from config, or optionally, and need checks |
| a pipeline of functions | each step has the same shape: data in, data out |
| generator chains | streams too big for memory: clean(parse(read(path))) |
scikit-learn Pipeline, pandas .pipe() |
data-science steps with fit / transform |
When not to use a builder: Request(url, headers={...}, params={...}) already reads well. A builder for three optional arguments is ceremony.
Adapter
Section titled “Adapter”class LegacyMailer: # third-party code you cannot change def deliver(self, recipient_list: list[str], body_text: str) -> int: return len(recipient_list)
class Notifier: # the interface your code expects: notify(user, message) def __init__(self, mailer: LegacyMailer) -> None: self._mailer = mailer
def notify(self, user: str, message: str) -> bool: return self._mailer.deliver([f"{user}@example.com"], message) == 1
print(Notifier(LegacyMailer()).notify("ada", "Your order shipped"))TrueAdapters keep a third-party API at the edge of your code: when the library changes, only the adapter changes. Tests replace the adapter with a fake.
When not to use: you own both sides (rename the method), or the wrapper only forwards every call unchanged.
Decorator pattern vs Python decorators
Section titled “Decorator pattern vs Python decorators”| Decorator pattern | Python decorator (@) |
|
|---|---|---|
| Wraps | an object, keeping its interface | a function or a class, at definition time |
| Chosen | at run time: Logged(Cached(storage)) |
when the code is written: @cache |
| Form | a class with the same methods that holds the inner object | a function that takes and returns a function |
| Examples | io.BufferedReader(raw), gzip.GzipFile(fileobj=f) |
@functools.cache, @retry, @app.get("/") |
import functoolsfrom collections.abc import Callable
class DictStorage: def __init__(self) -> None: self.data = {"a": "1"} self.reads = 0
def get(self, key: str) -> str | None: self.reads += 1 return self.data.get(key)
class CachedStorage: # decorator pattern: same get(), adds caching def __init__(self, inner: DictStorage) -> None: self._inner = inner self._cache: dict[str, str | None] = {}
def get(self, key: str) -> str | None: if key not in self._cache: self._cache[key] = self._inner.get(key) return self._cache[key]
def logged[**P, R](func: Callable[P, R]) -> Callable[P, R]: # a Python decorator @functools.wraps(func) # keep the name and the docstring def wrapper(*args: P.args, **kwargs: P.kwargs) -> R: result = func(*args, **kwargs) print(f"{func.__name__}{args} -> {result!r}") return result
return wrapper
@loggeddef add(a: int, b: int) -> int: return a + b
raw = DictStorage()store = CachedStorage(raw)print(store.get("a"), store.get("a"), store.get("z"), raw.reads)add(2, 3)1 1 None 2add(2, 3) -> 5When not to use the pattern: a function decorator already does it, or the wrapper must forward dozens of methods (consider __getattr__ delegation or subclassing instead).
Singleton as a module
Section titled “Singleton as a module”# config.py: the module is the singleton; Python imports it once per processimport osfrom dataclasses import dataclass
@dataclass(frozen=True)class Settings: database_url: str debug: bool = False
settings = Settings( database_url=os.environ.get("DATABASE_URL", "sqlite:///dev.db"), debug=os.environ.get("DEBUG") == "1",)
# elsewhere:# from config import settings# connect(settings.database_url)| Need | Python form |
|---|---|
| one shared configuration | a module-level object |
| one lazily built expensive object | @functools.cache on a zero-argument function: get_client() |
| one instance per class, enforced | rarely needed; a __new__ that caches is possible but surprising |
| reset between tests | inject the object, or call get_client.cache_clear() |
When not to use: a global that functions read implicitly makes tests depend on each other. Pass the object as a parameter wherever you can; keep the module-level object for main() and the framework entry points.
Dependency injection
Section titled “Dependency injection”from collections.abc import Callablefrom datetime import UTC, datetime
type Fetch = Callable[[str], list[dict[str, object]]]
def daily_report( *, fetch: Fetch, # required dependency now: Callable[[], datetime] = lambda: datetime.now(UTC), # default: the real clock log: Callable[[str], None] = print, # default: the console) -> int: orders = fetch("/orders?status=paid") stamp = now().date().isoformat() log(f"{stamp}: {len(orders)} paid orders") return len(orders)
lines: list[str] = []count = daily_report( fetch=lambda path: [{"id": 1}, {"id": 2}], # a fake API client now=lambda: datetime(2024, 5, 1, tzinfo=UTC), # a fixed clock log=lines.append, # capture the output)print(count, lines)2 ['2024-05-01: 2 paid orders']| Form | Example |
|---|---|
| a parameter with a production default | def job(*, log=print) |
| a constructor argument | UserService(repo=SqlRepo(engine)) |
| a factory from config | make_exporter(config["format"]) |
| a composition root | main() builds the real clients and passes them down |
| framework support | FastAPI Depends(get_db), pytest fixtures |
When not to use: pure functions with no I/O need nothing injected. Prefer injection to monkeypatch when you own the code; patching depends on how the function is written inside.
Gang of Four pattern → Python form
Section titled “Gang of Four pattern → Python form”| Pattern | Classic form | Python form |
|---|---|---|
| Strategy | an interface + one class per algorithm | a function; key=, backoff= |
| Command | an object with execute() |
a function or a partial; a dataclass for undo data |
| Factory method / abstract factory | creator class hierarchies | a function, a @classmethod, a dict of classes |
| Singleton | a private constructor + instance() |
a module-level object, or @functools.cache |
| Iterator | hasNext() / next() classes |
__iter__ and generators |
| Decorator | a wrapper class per behavior | a function decorator or a wrapper object |
| Adapter | a wrapper class | the same; or a few functions |
| Observer | subject and observer interfaces | a list of callables |
| Template method | an abstract class with hooks | the same: ABC + @abstractmethod |
| Visitor | double dispatch | functools.singledispatch or match |
| Builder | director + builder classes | keyword arguments, dataclasses; a fluent builder for step-by-step assembly |
| Prototype | clone() methods |
copy.copy(), copy.deepcopy(), dataclasses.replace() |
| Proxy | a class with the same interface | __getattr__ delegation |
Over-engineering checklist
Section titled “Over-engineering checklist”| Sign | Simpler |
|---|---|
a class with __init__ and one method |
a function |
| an abstract base class with one subclass | no base; add it at the second subclass |
| a factory with one product | call the class |
| getters and setters | attributes; @property when a check is needed |
| a wrapper that only forwards calls | call the inner object |
| config options nobody sets | delete them (YAGNI: “you aren’t gonna need it”) |
| the third copy of a block | now extract it (rule of three) |
| a singleton class | a module-level object |
A class earns its place when it keeps state between calls (a client with a session, a model with learned parameters) or groups several operations on the same data.
Patterns in the wild
Section titled “Patterns in the wild”| Pattern | Standard library | Web and tools | Data science |
|---|---|---|---|
| Strategy | sorted(key=), re.sub(func), json.dumps(default=) |
Django password hashers, auth backends | metric=, scoring= |
| Factory / registry | codecs.lookup, logging.getLogger |
Flask @app.route, pytest plugins, entry points |
get_scorer("r2") |
| Template method | unittest.TestCase, Thread.run, logging.Handler.emit |
Django class-based views | TransformerMixin.fit_transform (calls your fit and transform), nn.Module.forward |
| Observer | logging handlers, atexit.register |
Django signals, Qt signals, webhooks | Keras / Lightning callbacks |
| Pipeline | generator chains, itertools |
middleware, Unix pipes | scikit-learn Pipeline, .pipe() |
| Builder | argparse.ArgumentParser.add_argument |
SQLAlchemy select().where(), Django QuerySet.filter().order_by() |
Polars lazy queries |
| Adapter | io.TextIOWrapper |
database drivers behind DB-API | pandas readers |
| Decorator | functools.cache, contextlib.contextmanager |
@app.get, @login_required |
@torch.no_grad() |
| Dependency injection | default parameters | FastAPI Depends, pytest fixtures |
random_state=, injected loaders |
Gotchas
Section titled “Gotchas”- Calling the strategy. Symptom:
backoff=exponential()raises aTypeErroror passes a number. Fix: pass the function itself:backoff=exponential. - Registry not filled. Symptom: “unknown exporter” for a class you wrote. Fix: the module with
@registermust be imported first. - Silent overwrite in a registry. Symptom: two classes under one name; the last one wins. Fix: raise on duplicates in the decorator.
- Shared instance in a registry or default argument. Symptom: state leaks between callers. Fix: store classes or factories; build fresh objects.
- Overriding the template. Symptom: a subclass skips validation or logging. Fix: override the hook, not the template method.
- A hook that calls the template. Symptom:
RecursionError. Fix: hooks do one step only. - Observer failures. Symptom: one handler raises and the rest never run. Fix: decide on purpose: catch and log per handler, or let it propagate.
- Observers that keep state. Symptom: the second run reports the first run’s data. Fix: reset state in a start event, or create a fresh observer per run.
- Builder without
return self. Symptom:AttributeError: 'NoneType' object has no attribute 'header'. Fix: every chain method returnsself. - Hidden globals. Symptom: tests pass alone and fail together. Fix: inject the dependency; reset module-level caches in fixtures.
- Decorator without
functools.wraps. Symptom: every function is namedwrapperin logs and tracebacks. Fix: add@functools.wraps(func). - Lambdas in configs. Symptom: a strategy cannot be saved as JSON or pickled. Fix: store a name and resolve it with a dict.
- Pattern for its own sake. Symptom: an interface, a factory and a builder for one class. Fix: write the simplest code; refactor when the second real case arrives.
Learn more
Section titled “Learn more”- Lesson: Design principles and patterns and its cheat sheet
- Python decorators: Decorators and context managers cheat sheet
- Interfaces: ABC vs Protocol; composition: Inheritance