22. Design principles and patterns — Cheat sheet
The essentials of module 22 on one page. Every runnable block on this page is checked against its output.
Quick lookup
Section titled “Quick lookup”| I want to… | Use… | Example |
|---|---|---|
| let the caller choose an algorithm | strategy: a function parameter | knn = KNNClassifier(distance=manhattan) |
| choose an algorithm from config text | a dict of functions | DISTANCES["manhattan"] |
| give a strategy settings | a callable object or functools.partial |
Minkowski(p=3), partial(weighted, w=[1, 2]) |
| build an object from a name | a factory over a registry dict | make_model("knn", n_neighbors=15) |
| let a class add itself to a registry | a registration decorator | @register("knn") |
| build objects in more than one way | an alternative constructor | Dataset.from_csv(path, ...) |
| fix the steps, vary one step | template method + hook | fit() calls self._fit(X, y) |
| force subclasses to write the hook | ABC + @abstractmethod |
def _fit(self, X, y): ... |
| react to events without editing the loop | observer: a list of callbacks | fit(X, y, callbacks=[History()]) |
| let an observer stop the loop | an agreed flag | model.stop_training = True |
| chain steps with one interface | a pipeline | Pipeline([("scale", s), ("model", m)]) |
| assemble an object step by step | a builder with chainable methods | .add("scale", s).add("model", m).build() |
| make code testable without files | dependency injection | def job(*, read=read_csv_records, log=print) |
| collect log lines in a test | pass list.append |
job(log=lines.append) |
| accept only what a function uses | a small Protocol |
class SupportsPredict(Protocol): ... |
| keep one object for the whole program | a module-level object | settings = load_settings() in config.py |
| decide whether a pattern is worth it | YAGNI, rule of three | wait for the second or third real need |
Coupling and cohesion
Section titled “Coupling and cohesion”| 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 describe this unit’s job in one sentence without “and”? |
| Principle | Rule | Smell | Python fix |
|---|---|---|---|
| Single responsibility | one reason to change per unit | a class that reads, computes and formats | split into functions or classes by job |
| Open/closed | extend by adding code | 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 the parent works | an override that changes the meaning, raises NotImplementedError or rejects valid input |
keep the contract; add a new method or pass a strategy |
| Interface segregation | depend only on methods you use | a fat ABC; methods that only raise | several small Protocols |
| Dependency inversion | high-level code depends on abstractions | hard-coded paths, print(), clients built inside |
inject callables or objects; build them in main() |
Strategy
Section titled “Strategy”import mathfrom collections.abc import Callable, Sequencefrom functools import partial
type DistanceFunc = Callable[[Sequence[float], Sequence[float]], float]
def manhattan(a: Sequence[float], b: Sequence[float]) -> float: return sum(abs(x - y) for x, y in zip(a, b, strict=True))
def weighted(a: Sequence[float], b: Sequence[float], w: Sequence[float]) -> float: return math.sqrt(sum(wi * (x - y) ** 2 for x, y, wi in zip(a, b, w, strict=True)))
DISTANCES: dict[str, DistanceFunc] = {"euclidean": math.dist, "manhattan": manhattan}
def nearest(row: list[float], rows: list[list[float]], metric: DistanceFunc) -> int: return min(range(len(rows)), key=lambda i: metric(row, rows[i])) # the context
rows = [[0.0, 5.0], [3.0, 3.0]]print(nearest([0.0, 0.0], rows, DISTANCES["euclidean"])) # by name, from configprint(nearest([0.0, 0.0], rows, manhattan)) # a functionprint(nearest([0.0, 0.0], rows, partial(weighted, w=[1.0, 0.1]))) # with settings100| Strategy form | When |
|---|---|
| function | no settings: key=len, distance=manhattan |
partial or closure |
settings fixed once |
callable object (__call__) |
settings to show (__repr__) or change, or state |
| name in a dict | the choice comes from text (config, CLI, form) |
Store the strategy setting unchanged in __init__; resolve names in fit(), so get_params() and set_params() keep working.
Factory and registry
Section titled “Factory and registry”from typing import Any
MODELS: dict[str, type] = {}
def register(name: str) -> Callable[[type], type]: def decorator(cls: type) -> type: old = MODELS.get(name) if old is not None and old.__qualname__ != cls.__qualname__: raise ValueError(f"model name {name!r} is already registered") MODELS[name] = cls return cls # return the class unchanged
return decorator
def make_model(name: str, **params: Any) -> Any: try: cls = MODELS[name] except KeyError: known = sorted(MODELS) raise ValueError(f"unknown model {name!r}; choose from {known}") from None return cls(**params) # a fresh object on every call
@register("constant")class ConstantModel: def __init__(self, value: float = 0.0) -> None: self.value = value
print(make_model("constant", value=3.5).value, sorted(MODELS))try: make_model("knnn")except ValueError as err: print(err)3.5 ['constant']unknown model 'knnn'; choose from ['constant']- A class registers when its
classstatement runs, that is, when its module is imported. Import every model module in the package__init__.py. - Register classes, not instances: an instance would be shared by every caller.
- Plugins from other packages: entry points (
[project.entry-points."minilearn.models"]inpyproject.toml) andimportlib.metadata.entry_points(group="minilearn.models").
Template method
Section titled “Template method”from abc import ABC, abstractmethodfrom typing import Self
class Estimator(ABC): def fit(self, X: list[list[float]], y: list[float]) -> Self: # the template if len(X) != len(y): raise ValueError(f"{type(self).__name__}: {len(X)} rows, {len(y)} targets") self._fit(X, y) # the hook return self
@abstractmethod def _fit(self, X: list[list[float]], y: list[float]) -> None: ...
class MeanModel(Estimator): def _fit(self, X: list[list[float]], y: list[float]) -> None: self.mean_ = sum(y) / len(y)
print(MeanModel().fit([[1.0], [2.0]], [10.0, 20.0]).mean_)try: MeanModel().fit([[1.0]], [10.0, 20.0])except ValueError as err: print(err)15.0MeanModel: 1 rows, 2 targets| Do | Do not |
|---|---|
keep the template public; mark it @typing.final so mypy and pyright report overrides |
override fit() in a subclass |
name hooks _like_this |
call the template from a hook (endless recursion) |
mark required hooks @abstractmethod |
leave a required hook with a silent default |
| give optional hooks an empty default | copy the steps into each subclass |
Template methods you already use (in the standard library and other frameworks; scikit-learn’s estimators each write their own fit()): unittest.TestCase (setUp, test, tearDown), threading.Thread.run, Django ListView.get_queryset, PyTorch nn.Module.forward, logging.Handler.emit.
Observer
Section titled “Observer”class Callback: def on_epoch_end(self, model: Any, epoch: int, loss: float) -> None: """Empty default: an observer overrides only the events it needs."""
class History(Callback): def __init__(self) -> None: self.losses: list[float] = []
def on_epoch_end(self, model: Any, epoch: int, loss: float) -> None: self.losses.append(loss)
class StopBelow(Callback): def __init__(self, threshold: float) -> None: self.threshold = threshold
def on_epoch_end(self, model: Any, epoch: int, loss: float) -> None: if loss < self.threshold: model.stop_training = True # an observer talks back through a flag
class Trainer: # the subject def fit(self, callbacks: Sequence[Callback] = ()) -> Self: self.stop_training = False loss = 1.0 for epoch in range(1, 100): loss /= 2 # stands in for one pass over the data for cb in callbacks: cb.on_epoch_end(self, epoch, loss) if self.stop_training: break self.epochs_ = epoch return self
history = History()print(Trainer().fit([history, StopBelow(0.1)]).epochs_, history.losses)4 [0.5, 0.25, 0.125, 0.0625]| Observer form | When |
|---|---|
| a list of functions | one event: on_click=[save, log] |
a base class with empty on_* methods |
several events; observers override only some |
| a flag on the subject | an observer must change the flow (stop, skip) |
Reset an observer’s state in its start event, so one object serves several runs.
Pipeline and builder
Section titled “Pipeline and builder”class Builder: def __init__(self) -> None: self._steps: list[tuple[str, Any]] = []
def add(self, name: str, step: Any) -> Self: if any(n == name for n, _ in self._steps): raise ValueError(f"step {name!r} was already added") self._steps.append((name, step)) return self # fluent interface: calls chain
def build(self) -> list[tuple[str, Any]]: if not self._steps: raise ValueError("no steps") return list(self._steps)
steps = Builder().add("clean", str.strip).add("lower", str.lower).build()text = " Wireless EARBUDS "for _, step in steps: # a pipeline: each output is the next input text = step(text)print(repr(text), [name for name, _ in steps])'wireless earbuds' ['clean', 'lower']- A builder pays off when the object is assembled in a loop, from config or with optional steps, and each step needs a check.
- Otherwise use keyword arguments, a dataclass, or a factory function such as scikit-learn’s
make_pipeline(...). - Fit a whole pipeline on the training rows only: fitting a scaler before the split leaks test data.
Dependency injection
Section titled “Dependency injection”type Reader = Callable[[str], list[dict[str, str]]]
def churn_rate(path: str, *, read: Reader, log: Callable[[str], None] = print) -> float: records = read(path) rate = sum(r["churned"] == "1" for r in records) / len(records) log(f"{path}: {rate:.1%} churn") return rate
lines: list[str] = []fake = [{"churned": "1"}, {"churned": "0"}, {"churned": "0"}, {"churned": "0"}]rate = churn_rate("test.csv", read=lambda path: fake, log=lines.append)print(rate, lines)0.25 ['test.csv: 25.0% churn']| Form | Example |
|---|---|
| parameter with a production default | def job(*, log=print) |
| constructor argument | FitLogger(log=lines.append) |
| factory or config | make_model(config["model"]) |
| composition root | main() creates the real reader, logger and models |
Prefer injection to monkeypatch when you own the code: the test then does not depend 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 | interface + one class per algorithm | a function; key=, metric= |
| Command | an object with execute() |
a function or a partial |
| Factory method / abstract factory | a creator class hierarchy | a function, a @classmethod, a dict of classes |
| Singleton | private constructor + instance() |
a module-level object |
| Iterator | hasNext() / next() classes |
__iter__ / generators (module 10) |
| Decorator (pattern) | a wrapper class per behavior | a function decorator (module 11) or a wrapper object |
| Observer | subject + observer interfaces | a list of callables or on_* methods |
| Template method | 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 only for step-by-step assembly |
Over-engineering checklist
Section titled “Over-engineering checklist”| Sign | Simpler |
|---|---|
class with __init__ and one method |
function |
| abstract base with one subclass | no base; add it at the second subclass |
| 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) |
| the third copy of a block | now extract it (rule of three) |
A class earns its place when it keeps state between calls, such as parameters learned in fit() and used in predict().
Patterns in the wild
Section titled “Patterns in the wild”| Pattern | Standard library | Data science | Web, GUI and tools |
|---|---|---|---|
| Strategy | sorted(key=), re.sub(func) |
scikit-learn metric=, scoring=, criterion=; minilearn distance= |
Django password hashers |
| Factory / registry | codecs.lookup, logging.getLogger |
get_scorer("r2"), make_model |
Flask @app.route, pytest plugins |
| Template method | unittest.TestCase, Thread.run |
minilearn BaseEstimator.fit, PyTorch nn.Module.forward (scikit-learn’s BaseEstimator has no fit) |
Django class-based views |
| Observer | logging handlers, atexit |
Keras / Lightning callbacks, Optuna callbacks | Tkinter command=, Qt signals, Django signals |
| Pipeline | generator chains | scikit-learn Pipeline, pandas .pipe() |
Unix pipes, middleware |
| Builder | argparse.ArgumentParser.add_argument |
Polars lazy queries | SQLAlchemy select().where() |
| Dependency injection | default parameters | random_state=, injected loaders |
FastAPI Depends, pytest fixtures |
Gotchas
Section titled “Gotchas”distance=manhattan()calls the function. Passdistance=manhattan.- A duplicate-name check that rejects the same class breaks reruns of a notebook cell and
importlib.reload(). Compare__module__and__qualname__and accept the same class. - Resolving a strategy name in
__init__breaksset_params(). Resolve it infit(). - A subclass that overrides the template
fit()loses the checks and the callbacks. Override the hook. - A hook that calls the template recurses forever.
@registerruns at import time. An unimported module means an “unknown model”.- A registry or a default argument that holds an instance shares it with every caller. Store classes; build fresh objects.
- Two classes registered under one name replace each other silently, unless the decorator checks for duplicates.
- A callback that keeps state between runs must reset it in its start event.
- A slow callback runs inside the training loop and slows every epoch.
- A changed meaning in an override (an error from
score()) is silent: no exception, wrong decisions. - Fit scalers and imputers inside the pipeline, on training rows only, to avoid data leakage.
- Lambdas and closures cannot be saved as JSON and do not pickle; use names in configs.
- A pattern with one implementation is usually a smell in Python. A function is often enough.