Skip to content

22. Design principles and patterns

Modules 18 to 21 gave you the parts of object-oriented programming: classes, inheritance, special methods and dataclasses. This module is about how to arrange those parts so that code stays easy to change, test and extend. You meet the design ideas behind scikit-learn, Keras, Django and pytest, and you use them to finish minilearn: a model factory, training callbacks, a pipeline builder and one fixed fit() algorithm for every estimator. You also learn when a pattern is too much, and a plain function is the better design.

  • Explain coupling and cohesion, and apply the five SOLID principles to Python code: spot each violation and fix it.
  • Swap an algorithm at run time with the strategy pattern, usually with a plain function.
  • Build objects by name with a factory and a registry, so that a config file can choose the model.
  • Fix the steps of an algorithm in a base class with the template method pattern, and let subclasses fill in the hooks.
  • Notify any number of listeners with the observer pattern (training callbacks), and assemble steps with a pipeline and a builder.
  • Inject dependencies such as a loader or a logger to make code easy to test, and recognize when a pattern is over-engineering.

The examples continue minilearn, the small scikit-learn-like library of Part 3. They start from the code of modules 18 to 21, unchanged: the module 21 project’s classes, plus the MeanRegressor baseline of module 19. Open the block to see it, and paste it at the top of your script. It also loads the two course datasets (data dictionary) with the splits of the module 18 and module 21 projects: houses by sale date, and churn with a stratified test part and a validation part for choosing settings.

minilearn so far: the code of modules 18 to 21, and the data
minilearn_so_far.py
import csv
import inspect
import json
import math
import random
import statistics
from abc import ABC, abstractmethod
from collections import Counter
from collections.abc import Callable, Iterator, Sequence
from dataclasses import dataclass, field
from enum import StrEnum, auto
from typing import Any, NamedTuple, Protocol, Self, final, runtime_checkable
type Rows = list[list[float]]
type Row = Sequence[float] # one row of features: a list or a tuple
# --- metrics.py (modules 18 and 19) ---------------------------------------
def _check_lengths(y_true: list[float], y_pred: list[float]) -> None:
if len(y_true) != len(y_pred):
raise ValueError(f"lengths differ: {len(y_true)} vs {len(y_pred)}")
if not y_true:
raise ValueError("y_true is empty")
def mean_squared_error(y_true: list[float], y_pred: list[float]) -> float:
"""Mean of the squared differences between the truth and the predictions."""
_check_lengths(y_true, y_pred)
return sum((t - p) ** 2 for t, p in zip(y_true, y_pred, strict=True)) / len(y_true)
def r2_score(y_true: list[float], y_pred: list[float]) -> float:
"""1 - SS_res / SS_tot: the share of the variance of y that the model explains."""
_check_lengths(y_true, y_pred)
mean = sum(y_true) / len(y_true)
ss_res = sum((t - p) ** 2 for t, p in zip(y_true, y_pred, strict=True))
ss_tot = sum((t - mean) ** 2 for t in y_true)
if ss_tot == 0: # constant y_true: scikit-learn returns 1.0 or 0.0 here
return 1.0 if ss_res == 0 else 0.0
return 1 - ss_res / ss_tot
def accuracy_score(y_true: list[Any], y_pred: list[Any]) -> float:
"""Share of predictions that equal the true label."""
_check_lengths(y_true, y_pred)
return sum(t == p for t, p in zip(y_true, y_pred, strict=True)) / len(y_true)
# --- base.py (module 19; __repr__ and __eq__ from the module 20 lesson) ----
class NotFittedError(ValueError, AttributeError):
"""Raised when a model or transformer is used before fit()."""
def check_is_fitted(estimator: object) -> None:
"""Raise NotFittedError if the object has no learned attribute (name ending _)."""
learned = [k for k in vars(estimator) if k.endswith("_") and not k.startswith("__")]
if not learned:
name = type(estimator).__name__
raise NotFittedError(f"{name} is not fitted yet; call fit() first")
class BaseEstimator:
"""get_params() and set_params() for every estimator."""
@classmethod
def _get_param_names(cls) -> list[str]:
params = inspect.signature(cls.__init__).parameters.values()
return [
p.name
for p in params
if p.name != "self" and p.kind not in (p.VAR_POSITIONAL, p.VAR_KEYWORD)
]
def get_params(self) -> dict[str, Any]:
return {name: getattr(self, name) for name in self._get_param_names()}
def set_params(self, **params: Any) -> Self:
valid = self._get_param_names()
for name, value in params.items():
if name not in valid:
raise ValueError(
f"Invalid parameter {name!r} for {type(self).__name__}. "
f"Valid: {valid}"
)
setattr(self, name, value)
return self
def __repr__(self) -> str:
args = ", ".join(f"{k}={v!r}" for k, v in self.get_params().items())
return f"{type(self).__name__}({args})"
def __eq__(self, other: object) -> bool:
if not isinstance(other, BaseEstimator):
return NotImplemented
same_type = type(self) is type(other)
return same_type and self.get_params() == other.get_params()
class TransformerMixin:
"""fit_transform() for every transformer."""
def fit_transform(self, X: list[list[float]], y: Any = None) -> list[list[float]]:
return self.fit(X, y).transform(X)
class RegressorMixin:
"""score() as R² for every regressor."""
def score(self, X: list[list[float]], y: list[float]) -> float:
return r2_score(y, self.predict(X))
class ClassifierMixin:
"""score() as accuracy for every classifier."""
def score(self, X: list[list[float]], y: list[Any]) -> float:
return accuracy_score(y, self.predict(X))
# --- preprocessing.py and linear_model.py (module 19) ----------------------
class StandardScaler(TransformerMixin, BaseEstimator):
"""Standardize features: z = (x - mean_) / scale_, column by column."""
def __init__(self, with_mean: bool = True, with_std: bool = True) -> None:
self.with_mean = with_mean
self.with_std = with_std
def fit(self, X: list[list[float]], y: Any = None) -> Self:
if not X:
raise ValueError("cannot fit on an empty X")
n = len(X)
columns = list(zip(*X, strict=True))
means = [sum(col) / n for col in columns]
stds = [
self._population_std(col, mean)
for col, mean in zip(columns, means, strict=True)
]
self.mean_ = means if self.with_mean else [0.0] * len(columns)
self.scale_ = stds if self.with_std else [1.0] * len(columns)
self.n_features_in_ = len(columns)
return self
def transform(self, X: list[list[float]]) -> list[list[float]]:
self._check(X)
params = list(zip(self.mean_, self.scale_, strict=True))
return [
[(v - m) / s for v, (m, s) in zip(row, params, strict=True)] for row in X
]
def inverse_transform(self, Z: list[list[float]]) -> list[list[float]]:
self._check(Z)
params = list(zip(self.mean_, self.scale_, strict=True))
return [[z * s + m for z, (m, s) in zip(row, params, strict=True)] for row in Z]
@staticmethod
def _population_std(values: tuple[float, ...], mean: float) -> float:
variance = sum((v - mean) ** 2 for v in values) / len(values)
std = variance**0.5
return std if std > 0 else 1.0 # a constant column stays unchanged
def _check(self, X: list[list[float]]) -> None:
check_is_fitted(self)
for row in X:
if len(row) != self.n_features_in_:
raise ValueError(
f"X has {len(row)} features, but the scaler was fitted "
f"with {self.n_features_in_}"
)
class LinearRegression(RegressorMixin, BaseEstimator):
"""Fit y = coef_ * x + intercept_ for a single feature x."""
def __init__(self, fit_intercept: bool = True) -> None:
self.fit_intercept = fit_intercept
@staticmethod
def _single_column(X: list[list[float]]) -> list[float]:
for row in X:
if len(row) != 1:
raise ValueError(
f"LinearRegression supports exactly 1 feature, got {len(row)}"
)
return [row[0] for row in X]
def fit(self, X: list[list[float]], y: list[float]) -> Self:
x = self._single_column(X)
if len(x) != len(y) or len(x) < 2:
raise ValueError("X and y need the same length, with at least 2 samples")
if self.fit_intercept:
x_mean = sum(x) / len(x)
y_mean = sum(y) / len(y)
else:
x_mean = y_mean = 0.0
sxx = sum((xi - x_mean) ** 2 for xi in x)
sxy = sum((xi - x_mean) * (yi - y_mean) for xi, yi in zip(x, y, strict=True))
if sxx == 0:
raise ValueError("cannot fit a line: all x values are equal")
self.coef_ = sxy / sxx
self.intercept_ = y_mean - self.coef_ * x_mean
return self
def predict(self, X: list[list[float]]) -> list[float]:
check_is_fitted(self)
return [self.coef_ * x + self.intercept_ for x in self._single_column(X)]
# --- datasets.py (module 18; container methods from the module 20 lesson) ---
class Dataset:
"""Features X (one row per sample) and a target y (one value per sample)."""
def __init__(self, X: list[list[float]], y: list[float], feature_names: list[str]):
if not X:
raise ValueError("a Dataset needs at least one sample")
if len(X) != len(y):
raise ValueError(f"X has {len(X)} rows but y has {len(y)} values")
width = len(feature_names)
for i, row in enumerate(X):
if len(row) != width:
raise ValueError(f"row {i} has {len(row)} values, expected {width}")
self.X = X
self.y = y
self.feature_names = list(feature_names)
@property
def n_samples(self) -> int:
return len(self.X)
@property
def n_features(self) -> int:
return len(self.feature_names)
@staticmethod
def _parse(text: str, column: str, line: int) -> float | None:
"""Return the number in a CSV cell, or None for a blank cell."""
if not text.strip():
return None
try:
return float(text)
except ValueError:
message = f"line {line}: {column!r} is not a number: {text!r}"
raise ValueError(message) from None
@classmethod
def from_csv(
cls, path: str, target: str, features: list[str], skip_missing: bool = False
) -> Self:
"""Load the given feature columns and the target column of a CSV file.
A row with a blank cell in one of these columns raises ValueError, or is
skipped when skip_missing is True.
"""
X: list[list[float]] = []
y: list[float] = []
with open(path, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
header = reader.fieldnames or []
missing = [name for name in [*features, target] if name not in header]
if missing:
raise ValueError(f"{path}: unknown columns {missing}")
for line, row in enumerate(reader, start=2): # line 1 is the header
values = [cls._parse(row[name], name, line) for name in features]
label = cls._parse(row[target], target, line)
numbers = [v for v in values if v is not None]
if label is None or len(numbers) < len(values):
if skip_missing:
continue
raise ValueError(f"line {line}: blank value; use skip_missing=True")
X.append(numbers)
y.append(label)
return cls(X, y, features)
def column(self, name: str) -> list[float]:
"""Return the values of one feature."""
index = self.feature_names.index(name)
return [row[index] for row in self.X]
def split_at(self, n_first: int) -> tuple[Self, Self]:
"""Split into the first n_first samples and the rest, keeping the order."""
if not 0 < n_first < self.n_samples:
raise ValueError(f"n_first must be between 1 and {self.n_samples - 1}")
cls = type(self)
first = cls(self.X[:n_first], self.y[:n_first], self.feature_names)
rest = cls(self.X[n_first:], self.y[n_first:], self.feature_names)
return first, rest
def __repr__(self) -> str:
return f"Dataset(n_samples={len(self)}, features={self.feature_names!r})"
def __len__(self) -> int:
return len(self.X)
def __getitem__(self, key: int | slice | str) -> Any:
if isinstance(key, int): # one sample: (features, target)
return self.X[key], self.y[key]
if isinstance(key, slice): # a smaller Dataset
return type(self)(self.X[key], self.y[key], self.feature_names)
if isinstance(key, str): # one feature column, by name
if key not in self.feature_names:
raise KeyError(key)
return self.column(key)
kind = type(key).__name__
raise TypeError(f"Dataset indices must be int, slice or str, not {kind}")
def __iter__(self) -> Iterator[tuple[list[float], float]]:
yield from zip(self.X, self.y, strict=True)
# --- MajorityClassifier (module 19 project) ---------------------------------
class MajorityClassifier(ClassifierMixin, BaseEstimator):
"""Baseline: predict the most common training label (the smaller one on a tie)."""
def fit(self, X: list[list[float]], y: list[Any]) -> Self:
counts = Counter(y)
top = max(counts.values())
self.majority_ = min(label for label, n in counts.items() if n == top)
return self
def predict(self, X: list[list[float]]) -> list[Any]:
check_is_fitted(self)
return [self.majority_ for _ in X]
# --- model_selection.py (module 21) -----------------------------------------
@dataclass(frozen=True)
class Split:
"""The result of train_test_split: four read-only parts."""
X_train: tuple[tuple[float, ...], ...]
X_test: tuple[tuple[float, ...], ...]
y_train: tuple[Any, ...]
y_test: tuple[Any, ...]
test_indices: tuple[int, ...] = field(default=(), repr=False)
def __post_init__(self) -> None:
if len(self.X_train) != len(self.y_train):
raise ValueError("X_train and y_train have different lengths")
if len(self.X_test) != len(self.y_test):
raise ValueError("X_test and y_test have different lengths")
if not self.X_train or not self.X_test:
raise ValueError("both parts of a split need at least one row")
def __repr__(self) -> str:
return f"Split(n_train={len(self.X_train)}, n_test={len(self.X_test)})"
def __iter__(self) -> Iterator[tuple[Any, ...]]:
yield from (self.X_train, self.X_test, self.y_train, self.y_test)
def train_test_split(
X: Sequence[Row],
y: Sequence[Any],
*,
test_size: float = 0.25,
random_state: int | None = None,
stratify: Sequence[Any] | None = None,
) -> Split:
"""Shuffle the rows and split them into a training part and a test part."""
if len(X) != len(y):
raise ValueError(f"X has {len(X)} rows but y has {len(y)}")
if stratify is not None and len(stratify) != len(y):
raise ValueError(f"stratify has {len(stratify)} labels but y has {len(y)}")
if not 0 < test_size < 1:
raise ValueError(f"test_size must be in (0, 1), got {test_size}")
groups: dict[Any, list[int]] = {}
for i in range(len(y)):
key = None if stratify is None else stratify[i]
groups.setdefault(key, []).append(i)
rng = random.Random(random_state)
test_idx: list[int] = []
for key in sorted(groups, key=repr): # a fixed order, so the seed works
rows = groups[key]
rng.shuffle(rows)
test_idx.extend(rows[: round(len(rows) * test_size)])
test_idx.sort()
in_test = set(test_idx)
train_idx = [i for i in range(len(y)) if i not in in_test]
return Split(
X_train=tuple(tuple(X[i]) for i in train_idx),
X_test=tuple(tuple(X[i]) for i in test_idx),
y_train=tuple(y[i] for i in train_idx),
y_test=tuple(y[i] for i in test_idx),
test_indices=tuple(test_idx),
)
# --- Distance, Neighbor and KNNClassifier (module 21) -----------------------
class Distance(StrEnum):
"""How KNNClassifier measures the distance between two rows."""
EUCLIDEAN = auto() # "euclidean": straight-line distance
MANHATTAN = auto() # "manhattan": sum of the absolute differences
def __repr__(self) -> str:
return f"{type(self).__name__}.{self.name}" # valid Python, for model reprs
def between(self, a: Row, b: Row) -> float:
match self:
case Distance.EUCLIDEAN:
return math.dist(a, b)
case Distance.MANHATTAN:
return sum(abs(x - y) for x, y in zip(a, b, strict=True))
raise AssertionError(f"no formula for {self!r}")
class Neighbor(NamedTuple):
index: int # row number in the training data
distance: float
label: Any
class KNNClassifier(ClassifierMixin, BaseEstimator):
"""Majority vote of the k nearest training rows, with a choice of distance."""
def __init__(
self, n_neighbors: int = 5, distance: Distance | str = Distance.EUCLIDEAN
) -> None:
self.n_neighbors = n_neighbors
self.distance = distance # stored unchanged; validated in fit()
def fit(self, X: Sequence[Row], y: Sequence[Any]) -> Self:
if self.n_neighbors < 1:
raise ValueError(f"n_neighbors must be >= 1, got {self.n_neighbors}")
try:
self.distance_ = Distance(self.distance)
except ValueError:
valid = ", ".join(d.value for d in Distance)
msg = f"unknown distance {self.distance!r}; use one of: {valid}"
raise ValueError(msg) from None
self.X_train_ = [list(row) for row in X]
self.y_train_ = list(y)
self.classes_ = sorted(set(y))
return self
def kneighbors(self, row: Row) -> list[Neighbor]:
check_is_fitted(self)
pairs = zip(self.X_train_, self.y_train_, strict=True)
found = [
Neighbor(i, self.distance_.between(row, x), label)
for i, (x, label) in enumerate(pairs)
]
found.sort(key=lambda n: (n.distance, n.index)) # ties: lower row number
return found[: self.n_neighbors]
def predict(self, X: Sequence[Row]) -> list[Any]:
check_is_fitted(self)
predictions = []
for row in X:
votes = Counter(n.label for n in self.kneighbors(row))
predictions.append(max(self.classes_, key=lambda label: votes[label]))
return predictions
# --- metrics.py (module 21) --------------------------------------------------
def confusion_matrix(
y_true: Sequence[Any], y_pred: Sequence[Any], labels: Sequence[Any] | None = None
) -> list[list[int]]:
"""Rows are true classes, columns are predicted classes."""
if labels is None:
labels = sorted(set(y_true) | set(y_pred))
position = {label: j for j, label in enumerate(labels)}
matrix = [[0] * len(labels) for _ in labels]
for t, p in zip(y_true, y_pred, strict=True):
matrix[position[t]][position[p]] += 1
return matrix
@dataclass(frozen=True, slots=True)
class ClassMetrics:
label: str
precision: float
recall: float
f1: float
support: int
@dataclass(frozen=True)
class ClassificationReport:
classes: tuple[ClassMetrics, ...]
accuracy: float
macro_avg: ClassMetrics
weighted_avg: ClassMetrics
def __str__(self) -> str:
def line(m: ClassMetrics) -> str:
scores = f"{m.precision:>9.3f} {m.recall:>6.3f} {m.f1:>5.3f}"
return f"{m.label:>12} {scores} {m.support:>7}"
n = self.macro_avg.support
lines = [f"{'':>12} {'precision':>9} {'recall':>6} {'f1':>5} {'support':>7}"]
lines += [line(m) for m in self.classes]
lines.append(f"{'accuracy':>12} {'':>9} {'':>6} {self.accuracy:>5.3f} {n:>7}")
lines += [line(self.macro_avg), line(self.weighted_avg)]
return "\n".join(lines)
def _safe_ratio(numerator: float, denominator: float) -> float:
return numerator / denominator if denominator else 0.0
def classification_report(
y_true: Sequence[Any], y_pred: Sequence[Any]
) -> ClassificationReport:
labels = sorted(set(y_true) | set(y_pred))
matrix = confusion_matrix(y_true, y_pred, labels)
per_class = []
for j, label in enumerate(labels):
tp = matrix[j][j]
precision = _safe_ratio(tp, sum(row[j] for row in matrix)) # column sum
recall = _safe_ratio(tp, sum(matrix[j])) # row sum
f1 = _safe_ratio(2 * precision * recall, precision + recall)
support = sum(matrix[j])
per_class.append(ClassMetrics(str(label), precision, recall, f1, support))
def average(name: str, weights: list[int]) -> ClassMetrics:
def mean_of(attr: str) -> float:
pairs = zip(per_class, weights, strict=True)
return sum(getattr(m, attr) * w for m, w in pairs) / sum(weights)
precision, recall, f1 = mean_of("precision"), mean_of("recall"), mean_of("f1")
return ClassMetrics(name, precision, recall, f1, len(y_true))
return ClassificationReport(
classes=tuple(per_class),
accuracy=accuracy_score(list(y_true), list(y_pred)),
macro_avg=average("macro avg", [1] * len(per_class)),
weighted_avg=average("weighted avg", [m.support for m in per_class]),
)
# --- MeanRegressor (module 19 project) -------------------------------------
class MeanRegressor(RegressorMixin, BaseEstimator):
"""Baseline: predict the training mean for every row."""
def fit(self, X: list[list[float]], y: list[float]) -> Self:
self.mean_ = sum(y) / len(y)
return self
def predict(self, X: list[list[float]]) -> list[float]:
check_is_fitted(self)
return [self.mean_ for _ in X]
# --- the data ----------------------------------------------------------------
# House prices: the first 2,400 sales train, the newest 600 test (module 18).
houses = Dataset.from_csv("data/houses.csv", target="price", features=["sqft"])
old, new = houses.split_at(2400)
X_tr_h, y_tr_h, X_te_h, y_te_h = old.X, old.y, new.X, new.y
# Churn: every 4th customer, a stratified test part, and a validation part
# carved out of the training part for choosing settings (module 21).
features = ["tenure_months", "logins_last_30d"]
raw = Dataset.from_csv("data/customers.csv", target="churned", features=features)
sample = Dataset(raw.X, [int(v) for v in raw.y], raw.feature_names)[::4]
split = train_test_split(sample.X, sample.y, random_state=42, stratify=sample.y)
inner = train_test_split(
split.X_train, split.y_train, random_state=0, stratify=split.y_train
)
X_tr_c, X_te_c = [list(r) for r in split.X_train], [list(r) for r in split.X_test]
y_tr_c, y_te_c = list(split.y_train), list(split.y_test)
X_fit_c, X_val_c = [list(r) for r in inner.X_train], [list(r) for r in inner.X_test]
y_fit_c, y_val_c = list(inner.y_train), list(inner.y_test)
print(f"houses: {len(X_tr_h)} train, {len(X_te_h)} test")
print(f"customers: {len(X_fit_c)} fit + {len(X_val_c)} validation, {len(X_te_c)} test")
Output
houses: 2400 train, 600 test
customers: 704 fit + 234 validation, 312 test

A design principle is a rule of thumb for arranging code, such as “give each class one job”. A design pattern is a named, reusable solution to a design problem that keeps coming back, such as “let the user choose the algorithm at run time”. A pattern is not a library that you import. It is a shape that you recognize and adapt.

The 1994 book Design Patterns by Gamma, Helm, Johnson and Vlissides (the “Gang of Four”) named 23 patterns. It was written for C++ and Smalltalk. In Python, functions are objects that you can pass around and store in dicts (module 05). So several patterns shrink to a function, a dict or a decorator. This module shows the pattern and then its Python form.

Two words measure a design:

  • Coupling is how much one part of the code depends on the details of another part. With low coupling, you can change one part without breaking the other. A model that opens data/houses.csv itself is tightly coupled to that file.
  • Cohesion is how closely the contents of one class, function or module belong together. With high cohesion, a unit has one clear job. A metrics module with only metric functions is cohesive.

Aim for low coupling and high cohesion. Every principle and pattern in this module serves that aim.

Pattern Problem it solves Python form In minilearn Outside data science
Strategy choose an algorithm at run time pass a function KNNClassifier(distance=...) sorted(key=...), password hashers in Django
Factory and registry build an object from a name a dict and a decorator make_model("knn", n_neighbors=15) Flask @app.route, pytest plugins
Template method fix the steps, let subclasses vary one step a base method that calls hooks fit() calls _validate(), then _fit() unittest.TestCase.setUp, Django class-based views
Observer tell many listeners that something happened a list of callbacks training callbacks GUI button clicks, Django signals, logging handlers
Pipeline chain steps with the same interface a list of steps Pipeline Unix pipes, web middleware
Builder assemble a complex object step by step methods that return self Pipeline.builder().add(...) SQL query builders
Dependency injection let callers and tests choose the collaborators parameters with defaults FitLogger(log=print), read= FastAPI Depends, pytest fixtures

The sections below define every pattern, and the terms plugin and middleware of the last column.

SOLID is a set of five design principles collected by Robert C. Martin in the early 2000s. Each letter names one principle:

Letter Principle Rule Symptom of a violation
S Single responsibility A unit has one reason to change. One class reads files, computes and formats.
O Open/closed Add behavior by adding code, not by editing working code. A growing if/elif chain on a type name.
L Liskov substitution A subclass works wherever its parent works. A subclass that changes what an inherited method means.
I Interface segregation No code depends on methods it does not use. Classes that implement methods only to raise NotImplementedError.
D Dependency inversion High-level logic depends on abstractions, not on details. An experiment that hard-codes a file path and print().

The next five sections show each principle with a violation and its fix.

The single responsibility principle (SRP) says that a class or a function should have one reason to change. A “reason to change” is a requirement or a person who asks for changes: the data team changes the source, analysts change the metric, the dashboard team changes the format.

This class computes the churn rate per contract type. It has three jobs:

class ChurnReport:
"""Reads the file, computes the rates and formats the text: three jobs."""
def __init__(self, path: str) -> None:
self.path = path
def run(self) -> str:
with open(self.path, encoding="utf-8", newline="") as f:
records = list(csv.DictReader(f))
totals: dict[str, list[int]] = {}
for rec in records:
churned, count = totals.get(rec["contract"], [0, 0])
totals[rec["contract"]] = [churned + int(rec["churned"]), count + 1]
rows = [f"{k:<15} {c / n:6.1%}" for k, (c, n) in sorted(totals.items())]
return "\n".join(rows)
print(ChurnReport("data/customers.csv").run())
Output
month-to-month 29.6%
one-year 8.8%
two-year 3.2%

The result is right, but the design is fragile. To test the rate logic, you need a CSV file on disk. To show the rates by plan, you copy the method. To send HTML to a dashboard, you edit the same method that computes the rates, and you can break the numbers. Split the three jobs into three functions:

def read_csv_records(path: str) -> list[dict[str, str]]:
with open(path, encoding="utf-8", newline="") as f:
return list(csv.DictReader(f))
def churn_rate_by(records: list[dict[str, str]], column: str) -> dict[str, float]:
groups: dict[str, list[int]] = {}
for rec in records:
groups.setdefault(rec[column], []).append(int(rec["churned"]))
return {key: sum(flags) / len(flags) for key, flags in sorted(groups.items())}
def format_rates(rates: dict[str, float]) -> str:
return "\n".join(f"{name:<15} {rate:6.1%}" for name, rate in rates.items())
records = read_csv_records("data/customers.csv")
print(format_rates(churn_rate_by(records, "contract")))
print(
churn_rate_by(
[{"plan": "basic", "churned": "1"}, {"plan": "basic", "churned": "0"}], "plan"
)
)
Output
month-to-month 29.6%
one-year 8.8%
two-year 3.2%
{'basic': 0.5}

Each function now has one reason to change. churn_rate_by() takes the column as a parameter, so it reports by plan or region too. The last line tests it with two records typed in place, with no file at all. SRP does not mean “one method per class”. It means that the things in a unit change together, for the same reason.

The open/closed principle (OCP) says that code should be open for extension and closed for modification. You add a new behavior by adding new code, and you do not edit code that already works and is already tested.

The usual violation is an if/elif chain on a name:

def distance(a: Sequence[float], b: Sequence[float], kind: str = "euclidean") -> float:
if kind == "euclidean":
return math.dist(a, b)
if kind == "manhattan":
return sum(abs(x - y) for x, y in zip(a, b, strict=True))
raise ValueError(f"unknown distance {kind!r}")
print(distance([0, 0], [3, 4]), distance([0, 0], [3, 4], "manhattan"))
Output
5.0 7

Every new distance means one more branch in a function that works today. Module 21’s Distance.between() has the same shape: a match with one case per formula. Example 1 fixes it. The fix in Python is to pass the function itself. The code that uses a distance never changes again:

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 chebyshev(a: Sequence[float], b: Sequence[float]) -> float:
return max(abs(x - y) for x, y in zip(a, b, strict=True))
def nearest(
row: list[float], candidates: Rows, metric: DistanceFunc = math.dist
) -> int:
return min(range(len(candidates)), key=lambda i: metric(row, candidates[i]))
points = [[0.0, 5.0], [3.0, 3.0]]
for metric in (math.dist, manhattan, chebyshev):
index = nearest([0.0, 0.0], points, metric)
print(f"{metric.__name__:<10} nearest to [0, 0]: point {index}")
Output
dist nearest to [0, 0]: point 1
manhattan nearest to [0, 0]: point 0
chebyshev nearest to [0, 0]: point 1

The Manhattan distance adds the absolute differences of the coordinates, like a taxi that drives along a street grid. The Chebyshev distance takes the largest absolute difference. The three distances disagree about which point is nearest, so the choice matters. To add a fourth distance, you write a new function. nearest() stays closed: nobody edits it.

The Liskov substitution principle (LSP), named after Barbara Liskov, says that code that works with a class must also work with any of its subclasses. A subclass may add methods and accept more inputs. It must not change what an inherited method means.

pick_best() picks the model with the highest score(), because every minilearn score() means “higher is better”. This subclass breaks that promise:

class MSEMeanRegressor(MeanRegressor):
"""Breaks the contract: score() returns an error, where lower is better."""
def score(self, X: Rows, y: list[float]) -> float:
return mean_squared_error(y, self.predict(X))
def pick_best(models: list[Any], X_tr: Rows, y_tr: list, X_te: Rows, y_te: list) -> Any:
return max(models, key=lambda m: m.fit(X_tr, y_tr).score(X_te, y_te))
models = [MeanRegressor(), LinearRegression(), MSEMeanRegressor()]
for model in models:
print(f"{model!r:<37} score {model.fit(X_tr_h, y_tr_h).score(X_te_h, y_te_h):,.3f}")
print("best:", pick_best(models, X_tr_h, y_tr_h, X_te_h, y_te_h))
Output
MeanRegressor() score -0.014
LinearRegression(fit_intercept=True) score 0.561
MSEMeanRegressor() score 122,096,932,041.146
best: MSEMeanRegressor()

The mean baseline is the worst model, but its MSE is a huge number, so max() picks it. No error appears: the bug is silent. The fix is to keep the meaning of score() and to ask for other numbers by name. scikit-learn solves the same problem with its scorer neg_mean_squared_error: it negates the error, so that higher is still better.

def neg_mse(y_true: list[float], y_pred: list[float]) -> float:
return -mean_squared_error(y_true, y_pred) # negated: higher is better
def pick_best(
models: list[Any],
X_tr: Rows,
y_tr: list,
X_te: Rows,
y_te: list,
scoring: Callable[[list, list], float] | None = None,
) -> Any:
def score(model: Any) -> float:
model.fit(X_tr, y_tr)
if scoring is None:
return model.score(X_te, y_te)
return scoring(y_te, model.predict(X_te))
return max(models, key=score)
models = [MeanRegressor(), LinearRegression()]
print("best by R²:", pick_best(models, X_tr_h, y_tr_h, X_te_h, y_te_h))
print(
"best by MSE:", pick_best(models, X_tr_h, y_tr_h, X_te_h, y_te_h, scoring=neg_mse)
)
Output
best by R²: LinearRegression(fit_intercept=True)
best by MSE: LinearRegression(fit_intercept=True)

Other common violations: a subclass that raises NotImplementedError for an inherited method, that rejects inputs the parent accepts, or that returns another type (a dict where the parent returns a list). A type checker such as mypy reports an override whose signature does not fit the parent’s (module 12).

The interface segregation principle (ISP) says that no code should be forced to depend on methods it does not use. An interface is the set of methods that a piece of code expects from an object. Many small interfaces are better than one large one.

This abstract base class asks every estimator for fit, predict and transform. A scaler cannot predict anything:

class FatEstimator(ABC):
@abstractmethod
def fit(self, X: Rows, y: list | None = None) -> Self: ...
@abstractmethod
def predict(self, X: Rows) -> list: ...
@abstractmethod
def transform(self, X: Rows) -> Rows: ...
class MinMaxScaler(FatEstimator):
"""Scale each column to the range 0 to 1."""
def fit(self, X: Rows, y: list | None = None) -> Self:
self.low_ = [min(col) for col in zip(*X, strict=True)]
self.high_ = [max(col) for col in zip(*X, strict=True)]
return self
def transform(self, X: Rows) -> Rows:
pairs = list(zip(self.low_, self.high_, strict=True))
return [
[(v - lo) / (hi - lo) for v, (lo, hi) in zip(row, pairs, strict=True)]
for row in X
]
scaler = MinMaxScaler()
Output
TypeError: Can't instantiate abstract class MinMaxScaler without an implementation for abstract method 'predict'

The class statement succeeds, but Python refuses to create an instance, because predict is still abstract. The usual workaround, def predict(self, X): raise NotImplementedError, hides the problem and breaks the Liskov principle: code that calls predict() on any FatEstimator now crashes for some of them. The fix is several small interfaces. In Python, these are Protocols (modules 12 and 19). A function asks only for what it uses:

@runtime_checkable
class SupportsFit(Protocol):
def fit(self, X: Rows, y: Any = None) -> Any: ...
@runtime_checkable
class SupportsTransform(Protocol):
def transform(self, X: Rows) -> Rows: ...
@runtime_checkable
class SupportsPredict(Protocol):
def predict(self, X: Rows) -> list: ...
def transform_all(steps: list[SupportsTransform], X: Rows) -> Rows:
for step in steps:
X = step.transform(X)
return X
for est in (StandardScaler(), LinearRegression(), KNNClassifier()):
fit, trans, pred = (
isinstance(est, p) for p in (SupportsFit, SupportsTransform, SupportsPredict)
)
print(f"{type(est).__name__:<17} fit={fit} transform={trans} predict={pred}")
Output
StandardScaler fit=True transform=True predict=False
LinearRegression fit=True transform=False predict=True
KNNClassifier fit=True transform=False predict=True

The standard library follows the same rule. collections.abc defines Sized (only __len__), Iterable (only __iter__) and Container (only __contains__), not one large “collection” class.

The dependency inversion principle (DIP) says that high-level logic should not depend on low-level details. Both should depend on abstractions: descriptions of what is needed, such as “a function that returns X and y”. The experiment logic (fit on the old sales, score on the new ones) is high level. Reading a CSV file and printing are details.

class PriceExperiment:
def run(self) -> None:
data = Dataset.from_csv("data/houses.csv", "price", ["sqft"]) # a detail
model = LinearRegression().fit(data.X[:2400], data.y[:2400]) # a detail
print(f"R² {model.score(data.X[2400:], data.y[2400:]):.3f}") # a detail
PriceExperiment().run()
Output
R² 0.561

The class works, but you cannot run it on other data, with another model or without printing. Invert the dependencies: the experiment receives a loader, a model and a log function. It depends only on their shapes.

type Loader = Callable[[], tuple[Rows, list[float]]]
type Log = Callable[[str], None]
def run_price_experiment(
load: Loader, model: Any, log: Log = print, n_train: int = 2400
) -> float:
X, y = load()
model.fit(X[:n_train], y[:n_train])
r2 = model.score(X[n_train:], y[n_train:])
log(f"{model!r}: R² {r2:.3f}")
return r2
def load_houses() -> tuple[Rows, list[float]]:
data = Dataset.from_csv("data/houses.csv", "price", ["sqft"])
return data.X, data.y
run_price_experiment(load_houses, LinearRegression())
lines: list[str] = []
tiny = ([[1.0], [2.0], [3.0], [4.0]], [10.0, 20.0, 30.0, 40.0])
run_price_experiment(lambda: tiny, LinearRegression(), log=lines.append, n_train=2)
print(lines)
Output
LinearRegression(fit_intercept=True): R² 0.561
['LinearRegression(fit_intercept=True): R² 1.000']

The first call is the real experiment. The second call is a test: four rows typed in place, and a list that collects the log lines instead of printing them. Passing the collaborators in as arguments is called dependency injection, the technique of module 11. DIP is the goal; dependency injection is the usual way to reach it.

flowchart LR
    subgraph Before
        E1["PriceExperiment"] --> F1["data/houses.csv"]
        E1 --> P1["print()"]
    end
    subgraph After
        E2["run_price_experiment"] --> A["Loader / Log<br/>(abstractions)"]
        R["load_houses, print"] -.->|match| A
        T["test data, lines.append"] -.->|match| A
    end

The strategy pattern puts each version of an algorithm behind the same interface, so that the code that uses it, the context, can switch between them at run time. The open/closed fix above is a strategy: nearest() is the context, and each distance function is a strategy.

In Python, a strategy is usually a plain function. You have used strategies since module 05: sorted(key=...) and max(key=...). You will meet many more in scikit-learn, such as KNeighborsClassifier(metric="manhattan") and GridSearchCV(scoring="r2"). Use a class only when the strategy has settings or state. A callable object (module 20) has both, and it still looks like a function to the context:

class Minkowski:
"""A distance with a setting: p=1 is Manhattan, p=2 is Euclidean."""
def __init__(self, p: float) -> None:
self.p = p
def __repr__(self) -> str:
return f"Minkowski(p={self.p})"
def __call__(self, a: Sequence[float], b: Sequence[float]) -> float:
total = sum(abs(x - y) ** self.p for x, y in zip(a, b, strict=True))
return total ** (1 / self.p)
for metric in (Minkowski(1), Minkowski(2), Minkowski(3)):
print(metric, round(metric([0.0, 0.0], [3.0, 4.0]), 3))
Output
Minkowski(p=1) 7.0
Minkowski(p=2) 5.0
Minkowski(p=3) 4.498
Strategy form Use it when Example
a function the algorithm has no settings manhattan, math.dist
a closure or functools.partial it has a few settings fixed once partial(weighted_distance, w=[1, 2])
a callable object it has settings to show or change, or state Minkowski(p=3)
a name looked up in a dict the choice comes from a config file distance="manhattan"

Factory and registry: build objects by name

Section titled “Factory and registry: build objects by name”

A factory is a function or a method whose job is to create objects, so that callers do not name the concrete class. You know two factories already: Dataset.from_csv() (an alternative constructor, module 18) and dict.fromkeys(). A registry (module 05) is a dict that maps names to classes or functions. Together, they let a text config choose the class:

SCALERS = {"standard": StandardScaler}
def make_scaler(name: str, **params: Any) -> Any:
return SCALERS[name](**params)
print(make_scaler("standard", with_mean=False))
Output
StandardScaler(with_mean=False, with_std=True)

This dict has one entry; Example 4 fills a real registry with every model. A registration decorator adds a class to the registry at the place where the class is defined. A new model then needs a new class and nothing else: the factory never changes (open/closed). This is how many plugin systems work. A plugin is code that a program finds and loads at run time without knowing it in advance. Installed packages can advertise plugins through entry points: named groups in pyproject.toml. Module 08 used one group, [project.scripts] (the console_scripts group), which tells the installer which commands to create. pytest finds plugins in the group pytest11, and the Flask command line finds extra commands in flask.commands. Example 4 builds the minilearn registry.

The template method pattern puts the steps of an algorithm, in order, in one method of a base class. Some steps are hooks: methods that subclasses override (module 19 used the hook _center). The base method is the template. Subclasses fill in the hooks and never copy the steps.

The base class calls the subclass, not the other way around. This idea is called inversion of control: the framework calls your code. You meet it everywhere:

  • unittest.TestCase runs setUp(), then your test method, then tearDown().
  • Django class-based views run the request steps and call your get_queryset().
  • PyTorch’s nn.Module.__call__ runs its hooks and calls your forward() (module 42).
  • threading.Thread.start() sets up a thread and calls your run().

In minilearn, fit() becomes the template. It validates the input, notifies the callbacks and calls the hook _fit(), which each estimator writes:

sequenceDiagram
    participant U as your code
    participant B as BaseEstimator.fit
    participant S as subclass
    U->>B: fit(X, y, callbacks)
    B->>B: _validate(X, y)
    B->>B: on_fit_start for each callback
    B->>S: _fit(X, y)
    S-->>B: sets coef_, mean_ ...
    B->>B: on_fit_end for each callback
    B-->>U: self

Keep the template method public and do not override it. Mark it with @typing.final (module 12): mypy and pyright then report any subclass that overrides it. Name the hooks with a leading underscore, so that callers do not call them directly.

Observer: tell many listeners that something happened

Section titled “Observer: tell many listeners that something happened”

The observer pattern lets one object, the subject, notify any number of observers when an event happens, such as “an epoch ended”. The subject keeps a list of observers and calls each one. It does not know what they do: one draws a chart, one saves a checkpoint, one stops the training. So you add a new behavior by adding an observer, and the training loop stays the same.

In machine learning, the observers are called training callbacks. Keras passes callbacks=[EarlyStopping()] to fit(). PyTorch Lightning, XGBoost, LightGBM and Optuna have the same idea. Outside data science, a GUI button notifies its click handlers (command= in Tkinter), a browser calls addEventListener handlers, Django sends signals (events that any code can subscribe to) such as post_save, and one logging logger feeds several handlers (screen, file, email).

In Python, an observer can be a plain function. A base class with empty methods is useful when there are several events: an observer then overrides only the events it needs.

flowchart LR
    L["training loop<br/>(subject)"] -->|on_epoch_end| H["History<br/>records the loss"]
    L -->|on_epoch_end| P["PrintEvery<br/>prints a line"]
    L -->|on_epoch_end| S["EarlyStopping<br/>may stop training"]

The pipeline pattern chains steps that share one interface. The output of each step is the input of the next one. scikit-learn’s Pipeline chains transformers and a model. Unix pipes chain programs (grep ERROR app.log | sort | uniq -c). Web frameworks chain middleware: functions that each handle a request, then pass it on. Generator pipelines (module 10) chain lazy steps.

The builder pattern uses a separate object to assemble a complex object step by step, and to check it before it hands it over. Builders often use a fluent interface: each method returns self, so that calls chain, as in Pipeline.builder().add(...).add(...).build(). SQL query builders such as SQLAlchemy’s select(...).where(...).order_by(...) and pandas method chaining use the same chained style, but each call returns a new object instead of self.

Dependency injection (module 11) means that code receives its collaborators (a loader, a logger, a clock, a model) instead of creating them. Python needs no framework for it. There are three common forms:

Form Example Good for
a parameter with a default def churn_job(read=read_csv_records, log=print) functions; the default serves production
a constructor argument FitLogger(log=lines.append) objects that use the collaborator many times
a factory or a config make_model(config["model"]) choosing a class from text

The place where the program creates the real collaborators and connects them is the composition root. It is usually main(). Everywhere else, code takes what it is given. Tests then pass fakes (module 11): small stand-ins with controlled behavior. FastAPI’s Depends and pytest fixtures are dependency injection systems.

Over-engineering is design for needs that you do not have. It costs reading time, test time and change time, now, for a benefit that may never come. Three rules keep a design small:

  • YAGNI (“You aren’t gonna need it”): do not add a feature or an abstraction until a real need appears.
  • KISS (“Keep it simple”): prefer the simplest design that works.
  • The rule of three: copy code once if you must. When the third copy appears, extract the shared part. By then you know what really varies.

Many patterns come from languages where functions are not values. In Python, a pattern copied in its class-heavy C++ or Java form is often a code smell: a sign that the code is more complex than it needs to be.

Smell Simpler Python
a class with __init__ and one method a function
a Strategy class hierarchy with one method each a function per strategy, passed as an argument
a singleton class a module: it is imported once, so its objects exist once
a Factory class with one create() method a dict of classes, or a @classmethod
get_x() and set_x() methods a plain attribute, or @property when you need checks
an abstract base class with one subclass no base class; add one when the second subclass appears
a builder for an object with three settings keyword arguments, or a dataclass
layers that only pass calls on call the inner object directly

A pattern earns its place when it removes a real, repeated pain: duplicated checks, an if chain that keeps growing, code that you cannot test. “A function is often enough” is the default. Classes are for state that lives between calls, such as the median that a model learned in fit().

classDiagram
    class BaseEstimator {
        +fit(X, y, callbacks)
        +get_params()
        +set_params()
        #_validate(X, y)
        #_fit(X, y)*
    }
    class Callback {
        +on_fit_start()
        +on_fit_end()
    }
    class Pipeline {
        +fit()
        +predict()
        +builder()$
    }
    BaseEstimator <|-- StandardScaler
    BaseEstimator <|-- LinearRegression
    BaseEstimator <|-- KNNClassifier
    BaseEstimator ..> Callback : notifies
    KNNClassifier ..> DistanceFunc : strategy
    Pipeline o-- BaseEstimator : steps
    Registry ..> BaseEstimator : make_model()

All examples run in one script, top to bottom, after the “minilearn so far” block. Each one adds a pattern to minilearn or to a data job.

Example 1 — Swap distance strategies in a KNN churn model

Section titled “Example 1 — Swap distance strategies in a KNN churn model”

Goal: A KNN model decides which customers are “near” with a distance. Module 21 gave KNNClassifier a distance setting, but the formulas sit in one match inside Distance.between(). Let the analyst add a distance without editing that method, or pass any function, and compare the choices on the validation part.

Step 1 — Move the formulas into a strategy dict

Section titled “Step 1 — Move the formulas into a strategy dict”

In the “minilearn so far” block, Distance.between() has one case per formula. That is the open/closed violation of the concepts: a third distance means editing a method that works. Move each formula into a function and map the names to the functions:

DISTANCES: dict[str, DistanceFunc] = {
"euclidean": math.dist,
"manhattan": manhattan,
"chebyshev": chebyshev, # a new distance: one function, one entry
}
def get_distance(distance: Distance | str | DistanceFunc) -> DistanceFunc:
"""Accept a Distance member, a registered name or any distance function."""
if callable(distance):
return distance
try:
return DISTANCES[distance]
except KeyError:
valid = ", ".join(sorted(DISTANCES))
msg = f"unknown distance {distance!r}; use one of: {valid}"
raise ValueError(msg) from None
print(sorted(DISTANCES))
print(
get_distance(Distance.MANHATTAN)([0, 0], [3, 4]),
get_distance("chebyshev")([0, 0], [3, 4]),
)
print(Distance.MANHATTAN.between([0, 0], [3, 4])) # module 21's method still works
Output
['chebyshev', 'euclidean', 'manhattan']
7 4
7

The dict maps names, which a config file can hold, to functions, which the code can call. A StrEnum member is a string, so Distance.MANHATTAN and "manhattan" find the same entry. (With module 21’s lesson version, a plain Enum, the key would have to be .value.) get_distance() accepts a member, a name or a function, and an unknown name gets module 21’s message with the valid choices. The package of the mini-project keeps between() too, as a one-line lookup in this dict.

Step 2 — Let KNNClassifier call any distance function

Section titled “Step 2 — Let KNNClassifier call any distance function”
class KNNClassifier(KNNClassifier): # extend module 21's class
"""Majority vote of the k nearest rows, with a distance strategy."""
def fit(self, X: Sequence[Row], y: Sequence[Any]) -> Self:
if self.n_neighbors < 1:
raise ValueError(f"n_neighbors must be >= 1, got {self.n_neighbors}")
self.distance_ = get_distance(self.distance) # the strategy
self.X_train_ = [list(row) for row in X]
self.y_train_ = list(y)
self.classes_ = sorted(set(y))
return self
def kneighbors(self, row: Row) -> list[Neighbor]:
check_is_fitted(self)
pairs = zip(self.X_train_, self.y_train_, strict=True)
found = [
Neighbor(i, self.distance_(row, x), label) # call the strategy
for i, (x, label) in enumerate(pairs)
]
found.sort(key=lambda n: (n.distance, n.index)) # ties: lower row number
return found[: self.n_neighbors]
print(KNNClassifier())
print(KNNClassifier(n_neighbors=15, distance="chebyshev"))
Output
KNNClassifier(n_neighbors=5, distance=Distance.EUCLIDEAN)
KNNClassifier(n_neighbors=15, distance='chebyshev')

The model is the context. kneighbors() calls self.distance_(row, x) and does not know which function it holds; predict() from module 21 votes over kneighbors() unchanged. The constructor, also unchanged, stores distance as given, so repr(), get_params() and set_params() keep working. fit() turns the setting into a function.

Step 3 — Compare the strategies on the validation part

Section titled “Step 3 — Compare the strategies on the validation part”
fit_scaler = StandardScaler().fit(X_fit_c)
X_fit_s, X_val_s = fit_scaler.transform(X_fit_c), fit_scaler.transform(X_val_c)
def churn_f1(y_true: list, y_pred: list) -> float:
return classification_report(y_true, y_pred).classes[1].f1 # the class 1
for distance in (Distance.EUCLIDEAN, Distance.MANHATTAN, "chebyshev"):
pred = (
KNNClassifier(n_neighbors=1, distance=distance)
.fit(X_fit_s, y_fit_c)
.predict(X_val_s)
)
print(f"{distance!r:<20} validation churn F1 {churn_f1(y_val_c, pred):.3f}")
Output
Distance.EUCLIDEAN validation churn F1 0.360
Distance.MANHATTAN validation churn F1 0.368
'chebyshev' validation churn F1 0.348

The loop changes one argument per model. The comparison uses the validation part: 234 rows carved out of the training part, exactly as in the module 21 project. The test part plays no role in the choice. A setting chosen by its test score would make that score too optimistic, because the choice has already adapted to those rows. The features are scaled first, because a distance adds up the features, and the widest feature would dominate. The churn F1 score (module 21) balances precision and recall for the churners; accuracy would hide them.

Step 4 — Add a strategy without editing the class

Section titled “Step 4 — Add a strategy without editing the class”
def weighted(weights: list[float]) -> DistanceFunc:
"""A function factory: Euclidean distance with a weight per feature."""
def distance(a: Sequence[float], b: Sequence[float]) -> float:
pairs = zip(a, b, weights, strict=True)
return math.sqrt(sum(w * (x - y) ** 2 for x, y, w in pairs))
return distance
strategies = {"weighted([1, 3])": weighted([1.0, 3.0]), "Minkowski(3)": Minkowski(3)}
for label, distance in strategies.items():
knn = KNNClassifier(n_neighbors=1, distance=distance).fit(X_fit_s, y_fit_c)
print(
f"{label:<20} validation churn F1 {churn_f1(y_val_c, knn.predict(X_val_s)):.3f}"
)
Output
weighted([1, 3]) validation churn F1 0.353
Minkowski(3) validation churn F1 0.360

weighted() is a function factory (module 05). It returns a closure that multiplies the squared login difference by 3, so a login gap counts about 1.7 times (√3) as much as the same tenure gap. Minkowski(3) is the callable object from the concepts. Both plug into KNNClassifier with no change to its code: the class is closed for modification and open for extension.

Common mistakes:

  • Calling the strategy instead of passing it: distance=manhattan() raises TypeError because manhattan needs two arguments. Pass distance=manhattan.
  • Resolving the setting in __init__. Then set_params(distance="chebyshev") changes the attribute but not the function in use. Store the setting unchanged and resolve it in fit().
  • Choosing the distance by its score on the test part. Compare on a validation part or with cross-validation (module 37), and score the test part once, at the end.
  • Putting a lambda or a closure in a config that must be saved. Store names (strings) in configs: a name survives JSON and pickle. A module-level function pickles by reference but cannot go into JSON; lambdas and closures fit neither.

Example 2 — Watch gradient descent with training callbacks

Section titled “Example 2 — Watch gradient descent with training callbacks”

Goal: A model that learns in many passes over the data (epochs) should report its progress, record the loss for a chart and stop when it no longer improves. The training loop must not know about printing, charts or stopping rules.

Gradient descent learns a line step by step: it starts with a guess, measures the error (the loss, here the MSE), and moves the slope and the intercept a small step in the direction that lowers the loss. The step size is the learning rate. One pass over the training data is an epoch. Module 32 derives the formulas; here they are given.

Step 1 — Define the observer interface and two observers

Section titled “Step 1 — Define the observer interface and two observers”
class Callback:
"""Observer of training. Each event does nothing until a subclass overrides it."""
def on_fit_start(self, model: Any, X: Rows, y: list | None) -> None:
"""Called before the model learns."""
def on_epoch_end(self, model: Any, epoch: int, loss: float) -> None:
"""Called by iterative models after each pass over the data."""
def on_fit_end(self, model: Any) -> None:
"""Called after the model has learned."""
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 PrintEvery(Callback):
def __init__(self, every: int, log: Callable[[str], None] = print) -> None:
self.every = every
self.log = log
def on_epoch_end(self, model: Any, epoch: int, loss: float) -> None:
if epoch % self.every == 0:
self.log(f"epoch {epoch:>3} loss {loss:12,.1f}")

The base class defines three events with empty bodies. A docstring is a valid body, so the methods need no pass. History listens to one event and PrintEvery to another. Neither knows how the model learns.

Step 2 — Write a training loop that notifies its observers

Section titled “Step 2 — Write a training loop that notifies its observers”
class GradientDescentRegressor(RegressorMixin, BaseEstimator):
"""A line fitted step by step, for one feature."""
def __init__(self, learning_rate: float = 0.1, max_epochs: int = 200) -> None:
self.learning_rate = learning_rate
self.max_epochs = max_epochs
def fit(
self, X: Rows, y: list[float], *, callbacks: Sequence[Callback] = ()
) -> Self:
x = [row[0] for row in X]
n = len(x)
self.coef_, self.intercept_ = 0.0, 0.0
self.stop_training = False # an observer may set this to True
for cb in callbacks:
cb.on_fit_start(self, X, y)
for epoch in range(1, self.max_epochs + 1):
errors = [
self.intercept_ + self.coef_ * a - b for a, b in zip(x, y, strict=True)
]
self.coef_ -= (
self.learning_rate
* 2
/ n
* sum(e * a for e, a in zip(errors, x, strict=True))
)
self.intercept_ -= self.learning_rate * 2 / n * sum(errors)
loss = sum(e * e for e in errors) / n
for cb in callbacks:
cb.on_epoch_end(self, epoch, loss)
if self.stop_training:
break
self.n_epochs_ = epoch
for cb in callbacks:
cb.on_fit_end(self)
return self
def predict(self, X: Rows) -> list[float]:
check_is_fitted(self)
return [self.intercept_ + self.coef_ * row[0] for row in X]

The loop is the subject. After each epoch, it calls on_epoch_end on every callback, and then checks one flag, stop_training. That flag is the only way an observer can talk back. The same design is in Keras: its EarlyStopping callback sets model.stop_training = True.

Step 3 — Train with a history and a progress printer

Section titled “Step 3 — Train with a history and a progress printer”
sqft_scaler = StandardScaler().fit(X_tr_h)
X_gd = sqft_scaler.transform(X_tr_h)
y_gd = [price / 1000 for price in y_tr_h] # thousands of USD keep the loss readable
history = History()
gd = GradientDescentRegressor(learning_rate=0.1, max_epochs=60)
gd.fit(X_gd, y_gd, callbacks=[history, PrintEvery(20)])
exact = LinearRegression().fit(X_gd, y_gd)
print(
f"after {gd.n_epochs_} epochs: coef {gd.coef_:.1f}, closed form {exact.coef_:.1f}"
)
print(f"{len(history.losses)} losses recorded, last {history.losses[-1]:,.1f}")
Output
epoch 20 loss 46,297.3
epoch 40 loss 46,241.3
epoch 60 loss 46,241.3
after 60 epochs: coef 224.2, closed form 224.2
60 losses recorded, last 46,241.3

The scaler makes the feature small, so a learning rate of 0.1 is stable. The loss falls fast, then flattens. After 60 epochs, the slope matches the exact least-squares slope of LinearRegression to one decimal. history.losses now holds 60 numbers, ready for a learning-curve chart (module 28).

Step 4 — Stop early with an observer that talks back

Section titled “Step 4 — Stop early with an observer that talks back”
class EarlyStopping(Callback):
"""Stop when the loss has not improved by min_delta for `patience` epochs."""
def __init__(self, min_delta: float, patience: int = 3) -> None:
self.min_delta = min_delta
self.patience = patience
def on_fit_start(self, model: Any, X: Rows, y: list | None) -> None:
self.best, self.waited = math.inf, 0 # reset, so the callback can be reused
def on_epoch_end(self, model: Any, epoch: int, loss: float) -> None:
if loss < self.best - self.min_delta:
self.best, self.waited = loss, 0
else:
self.waited += 1
if self.waited >= self.patience:
model.stop_training = True
lines: list[str] = []
gd = GradientDescentRegressor(learning_rate=0.1, max_epochs=500)
gd.fit(
X_gd, y_gd, callbacks=[EarlyStopping(min_delta=1.0), PrintEvery(10, lines.append)]
)
print(f"stopped after {gd.n_epochs_} of 500 epochs; coef {gd.coef_:.1f}")
print(lines[-1])
Output
stopped after 32 of 500 epochs; coef 224.0
epoch 30 loss 46,242.0

EarlyStopping resets its counters in on_fit_start, so one object can serve several trainings. When the loss improves by less than 1.0 for three epochs in a row, it sets the flag, and the loop stops at the end of that epoch. PrintEvery now writes into a list through its injected log. Neither observer changed the training loop.

Common mistakes:

  • Giving the subject a fixed list of tasks (if self.verbose: print(...), if self.save_history: ...). Every new task then edits the training loop. Put each task in an observer.
  • Keeping state in a callback between trainings without a reset. A reused EarlyStopping would stop the second training at once. Reset in on_fit_start.
  • Doing slow work, such as writing a file, in on_epoch_end on every epoch. Observers run inside the loop, so they slow it down. Act every few epochs.

This fit() writes the steps itself: validation is missing, and the callback loops are copied into the model. Example 3 moves those steps into a template and ports this model onto it.

Example 3 — Put the fit checks in one place with a template method

Section titled “Example 3 — Put the fit checks in one place with a template method”

Goal: Every minilearn model should reject bad input with the same clear message, notify callbacks, and let an iterative model send epoch events, without copying the checks into six classes.

Step 1 — See five ways to handle the same bad input

Section titled “Step 1 — See five ways to handle the same bad input”
ragged = [[1500.0], [2100.0, 3.0], [900.0]] # the second row has 2 values
labels = [1, 0, 1]
for model in (
StandardScaler(),
LinearRegression(),
KNNClassifier(1),
MeanRegressor(),
MajorityClassifier(),
):
try:
model.fit(ragged, labels)
print(f"{type(model).__name__:<18} accepted the ragged rows")
except ValueError as err:
print(f"{type(model).__name__:<18} {err}")
Output
StandardScaler zip() argument 2 is longer than argument 1
LinearRegression LinearRegression supports exactly 1 feature, got 2
KNNClassifier accepted the ragged rows
MeanRegressor accepted the ragged rows
MajorityClassifier accepted the ragged rows

Each model of modules 18 to 21 checks its input in its own way, or not at all. One message is specific, one comes from deep inside zip(), and three models accept the broken row without a word. Adding the same checks to each fit() would copy them five times, and the sixth model would forget them.

Step 2 — Write the template in the base class

Section titled “Step 2 — Write the template in the base class”
def check_X(X: Sequence[Sequence[float]], owner: str) -> Rows:
if len(X) == 0:
raise ValueError(f"{owner}: X is empty")
width = len(X[0])
for i, row in enumerate(X):
if len(row) != width:
raise ValueError(
f"{owner}: row {i} has length {len(row)}, expected {width}"
)
return [[float(v) for v in row] for row in X]
class BaseEstimator(BaseEstimator, ABC): # extend the base of modules 19 to 21
"""fit() is a template method: subclasses write the hook _fit()."""
_requires_y = True # transformers set this to False
@final # mypy and pyright report any subclass that overrides fit()
def fit(
self,
X: Sequence[Row],
y: Sequence[Any] | None = None,
*,
callbacks: Sequence[Callback] = (),
) -> Self:
rows, labels = self._validate(X, y)
self._callbacks = tuple(callbacks) # the hook can send epoch events
self.stop_training = False # an observer may set this to True
for cb in self._callbacks:
cb.on_fit_start(self, rows, labels)
self._fit(rows, labels)
self.n_features_in_ = len(rows[0])
for cb in self._callbacks:
cb.on_fit_end(self)
self._callbacks = () # do not keep the observers after fit()
return self
def _notify_epoch(self, epoch: int, loss: float) -> None:
"""For iterative hooks: send on_epoch_end to the callbacks of this fit()."""
for cb in self._callbacks:
cb.on_epoch_end(self, epoch, loss)
def _validate(
self, X: Sequence[Row], y: Sequence[Any] | None
) -> tuple[Rows, list | None]:
name = type(self).__name__
rows = check_X(X, name)
if y is None:
if self._requires_y:
raise ValueError(f"{name}.fit() needs y")
return rows, None
if len(y) != len(rows):
raise ValueError(f"{name}: X has {len(rows)} rows but y has {len(y)}")
return rows, list(y)
def _check_input(self, X: Sequence[Row]) -> Rows:
check_is_fitted(self)
name = type(self).__name__
rows = check_X(X, name)
if len(rows[0]) != self.n_features_in_:
raise ValueError(
f"{name}: X has {len(rows[0])} features, "
f"but fit() saw {self.n_features_in_}"
)
return rows
@abstractmethod
def _fit(self, X: Rows, y: list | None) -> None:
"""The hook: learn from validated data and set attributes ending in _."""
class TransformerMixin:
_requires_y = False
def transform(self, X: Sequence[Row]) -> Rows:
return self._transform(self._check_input(X))
def fit_transform(
self,
X: Sequence[Row],
y: Sequence[Any] | None = None,
*,
callbacks: Sequence[Callback] = (),
) -> Rows:
return self.fit(X, y, callbacks=callbacks).transform(X)
class PredictorMixin:
def predict(self, X: Sequence[Row]) -> list:
return self._predict(self._check_input(X))
class RegressorMixin(PredictorMixin):
def score(self, X: Sequence[Row], y: Sequence[float]) -> float:
return r2_score(list(y), self.predict(X))
class ClassifierMixin(PredictorMixin):
def score(self, X: Sequence[Row], y: Sequence[Any]) -> float:
return accuracy_score(list(y), self.predict(X))

fit() fixes the steps and their order: validate, notify, learn, record n_features_in_, notify, return self. Only the learning step, _fit(), differs between models. While _fit() runs, the template keeps the callbacks in self._callbacks, so an iterative hook can call self._notify_epoch() and read self.stop_training. predict() and transform() follow the same idea with the hooks _predict() and _transform(), and both check the number of features. @abstractmethod makes a subclass without _fit() impossible to instantiate, and @typing.final (module 12) tells a type checker that no subclass may override fit(); Python itself does not enforce it at run time. The class statement reuses the name BaseEstimator: the new class extends the base of modules 19 to 21, so get_params(), __repr__ and __eq__ stay. check_is_fitted() is module 21’s, unchanged.

Step 3 — Rewrite the estimators with hooks only

Section titled “Step 3 — Rewrite the estimators with hooks only”
StandardScaler, LinearRegression, KNNClassifier, MeanRegressor, MajorityClassifier and GradientDescentRegressor on the template
class StandardScaler(TransformerMixin, BaseEstimator):
def __init__(self, with_mean: bool = True, with_std: bool = True) -> None:
self.with_mean = with_mean
self.with_std = with_std
def _fit(self, X: Rows, y: list | None) -> None:
columns = list(zip(*X, strict=True))
n = len(X)
means = [sum(col) / n for col in columns] # module 21's formulas, unchanged
stds = [
math.sqrt(sum((v - m) ** 2 for v in col) / n)
for col, m in zip(columns, means, strict=True)
]
self.mean_ = means if self.with_mean else [0.0] * len(columns)
self.scale_ = [s or 1.0 for s in stds] if self.with_std else [1.0] * len(stds)
def _transform(self, X: Rows) -> Rows:
return [
[(v - m) / s for v, m, s in zip(row, self.mean_, self.scale_, strict=True)]
for row in X
]
class LinearRegression(RegressorMixin, BaseEstimator):
def __init__(self, fit_intercept: bool = True) -> None:
self.fit_intercept = fit_intercept
def _fit(self, X: Rows, y: list[float]) -> None:
if len(X[0]) != 1:
raise ValueError(
f"LinearRegression supports exactly 1 feature, got {len(X[0])}"
)
x = [row[0] for row in X]
mean_x = statistics.fmean(x) if self.fit_intercept else 0.0
mean_y = statistics.fmean(y) if self.fit_intercept else 0.0
sxy = sum((a - mean_x) * (b - mean_y) for a, b in zip(x, y, strict=True))
sxx = sum((a - mean_x) ** 2 for a in x)
self.coef_ = sxy / sxx
self.intercept_ = mean_y - self.coef_ * mean_x
def _predict(self, X: Rows) -> list[float]:
return [self.intercept_ + self.coef_ * row[0] for row in X]
class KNNClassifier(ClassifierMixin, BaseEstimator):
def __init__(
self,
n_neighbors: int = 5,
distance: Distance | str | DistanceFunc = Distance.EUCLIDEAN,
) -> None:
self.n_neighbors = n_neighbors
self.distance = distance
def _fit(self, X: Rows, y: list) -> None:
if self.n_neighbors < 1:
raise ValueError(f"n_neighbors must be >= 1, got {self.n_neighbors}")
self.distance_ = get_distance(self.distance)
self.X_train_ = X
self.y_train_ = y
self.classes_ = sorted(set(y))
def kneighbors(self, row: Row) -> list[Neighbor]:
check_is_fitted(self)
pairs = zip(self.X_train_, self.y_train_, strict=True)
found = [
Neighbor(i, self.distance_(row, x), label)
for i, (x, label) in enumerate(pairs)
]
found.sort(key=lambda n: (n.distance, n.index))
return found[: self.n_neighbors]
def _predict(self, X: Rows) -> list:
votes = [Counter(n.label for n in self.kneighbors(row)) for row in X]
return [max(self.classes_, key=lambda label: v[label]) for v in votes]
class MeanRegressor(RegressorMixin, BaseEstimator):
def _fit(self, X: Rows, y: list[float]) -> None:
self.mean_ = statistics.fmean(y)
def _predict(self, X: Rows) -> list[float]:
return [self.mean_ for _ in X]
class MajorityClassifier(ClassifierMixin, BaseEstimator):
def _fit(self, X: Rows, y: list) -> None:
counts = Counter(y)
top = max(counts.values())
self.majority_ = min(label for label, n in counts.items() if n == top)
def _predict(self, X: Rows) -> list:
return [self.majority_ for _ in X]
class GradientDescentRegressor(RegressorMixin, BaseEstimator):
def __init__(self, learning_rate: float = 0.1, max_epochs: int = 200) -> None:
self.learning_rate = learning_rate
self.max_epochs = max_epochs
def _fit(self, X: Rows, y: list[float]) -> None:
x, n, lr = [row[0] for row in X], len(X), self.learning_rate
self.coef_, self.intercept_ = 0.0, 0.0
for epoch in range(1, self.max_epochs + 1):
errors = [
self.intercept_ + self.coef_ * a - b for a, b in zip(x, y, strict=True)
]
self.coef_ -= (
lr * 2 / n * sum(e * a for e, a in zip(errors, x, strict=True))
)
self.intercept_ -= lr * 2 / n * sum(errors)
self._notify_epoch(epoch, sum(e * e for e in errors) / n) # observers
if self.stop_training:
break
self.n_epochs_ = epoch
def _predict(self, X: Rows) -> list[float]:
return [self.intercept_ + self.coef_ * row[0] for row in X]

Each class is now shorter than before. None of them checks its input, calls check_is_fitted() or returns self: the template does all three. A model’s own rules stay in its hook, such as “one feature only” in LinearRegression._fit(). GradientDescentRegressor from Example 2 no longer writes the callback loops: its hook sends on_epoch_end through _notify_epoch(), and the template sends the start and end events.

Step 4 — See the same checks and callbacks on every model

Section titled “Step 4 — See the same checks and callbacks on every model”
class FitLogger(Callback):
def __init__(self, log: Callable[[str], None] = print) -> None:
self.log = log
def on_fit_start(self, model: Any, X: Rows, y: list | None) -> None:
self.log(f"fit {type(model).__name__}: {len(X)} rows x {len(X[0])} features")
for cls in (
StandardScaler,
LinearRegression,
KNNClassifier,
MeanRegressor,
MajorityClassifier,
):
try:
cls().fit(ragged, labels)
except ValueError as err:
print(err)
try:
KNNClassifier(15).fit(X_fit_s, y_fit_c).predict([[0.0, 1.0, 2.0]])
except ValueError as err:
print(err)
gd = GradientDescentRegressor(learning_rate=0.1, max_epochs=500)
gd.fit(X_gd, y_gd, callbacks=[FitLogger(), EarlyStopping(min_delta=1.0)])
print(f"stopped after {gd.n_epochs_} of 500 epochs; coef {gd.coef_:.1f}")
Output
StandardScaler: row 1 has length 2, expected 1
LinearRegression: row 1 has length 2, expected 1
KNNClassifier: row 1 has length 2, expected 1
MeanRegressor: row 1 has length 2, expected 1
MajorityClassifier: row 1 has length 2, expected 1
KNNClassifier: X has 3 features, but fit() saw 2
fit GradientDescentRegressor: 2400 rows x 1 features
stopped after 32 of 500 epochs; coef 224.0

The five models give the same kind of message, written once. FitLogger works with any model, because the template sends the events, not the model. EarlyStopping from Example 2 stops the ported model at the same epoch as before, now through the template: the refactoring kept the behavior. A seventh model gets all of this by writing one hook.

Common mistakes:

  • Overriding fit() in a subclass “just to add one line”. The checks and the callbacks then disappear for that model. Override the hook, or add a new hook to the template; @typing.final lets a type checker catch the override.
  • Calling self.fit() from _fit(). The template calls the hook; the hook must not call the template, or the recursion never ends.
  • Forgetting @abstractmethod on the hook. A subclass without _fit() then fails only when someone trains it, far from the mistake.

Example 4 — Build models by name from a config

Section titled “Example 4 — Build models by name from a config”

Goal: An experiment file names its models as text, such as "knn" with {"n_neighbors": 15}. A factory turns each name into a fresh estimator, and a new model class becomes available by adding it, with no edit to the factory.

Step 1 — Write the registry and its decorator

Section titled “Step 1 — Write the registry and its decorator”
MODELS: dict[str, type[BaseEstimator]] = {}
def register[E: type[BaseEstimator]](name: str) -> Callable[[E], E]:
def decorator(cls: E) -> E:
old = MODELS.get(name)
same = old is not None and (old.__module__, old.__qualname__) == (
cls.__module__,
cls.__qualname__,
)
if old is not None and not same:
raise ValueError(f"model name {name!r} is already used by {old.__name__}")
MODELS[name] = cls
return cls
return decorator
for name, cls in [
("scaler", StandardScaler),
("linear", LinearRegression),
("gd", GradientDescentRegressor),
("knn", KNNClassifier),
("mean", MeanRegressor),
("majority", MajorityClassifier),
]:
register(name)(cls)
@register("median")
class MedianRegressor(RegressorMixin, BaseEstimator):
"""Baseline: predict the training median for every row."""
def _fit(self, X: Rows, y: list[float]) -> None:
self.median_ = statistics.median(y)
def _predict(self, X: Rows) -> list[float]:
return [self.median_ for _ in X]
print(sorted(MODELS))
Output
['gd', 'knn', 'linear', 'majority', 'mean', 'median', 'scaler']

register(name) returns a decorator, and the decorator stores the class and returns it unchanged. A decorator is just a function, so the loop applies it to the classes that already exist. MedianRegressor uses the @register("median") line, as a new model would. The type parameter E (module 12) tells a type checker that the decorator returns the same class it receives.

def make_model(name: str, **params: Any) -> BaseEstimator:
try:
cls = MODELS[name]
except KeyError:
known = ", ".join(sorted(MODELS))
raise ValueError(f"unknown model {name!r}; choose from: {known}") from None
return cls(**params)
print(make_model("knn", n_neighbors=15, distance="manhattan"))
print(make_model("median"))
Output
KNNClassifier(n_neighbors=15, distance='manhattan')
MedianRegressor()
make_model("random_forest")
Output
ValueError: unknown model 'random_forest'; choose from: gd, knn, linear, majority, mean, median, scaler

The factory returns a new object on every call, so two experiments never share a fitted model. A typo gets a message that lists every valid name. from None hides the internal KeyError, which would only distract the reader.

Step 3 — Run experiments described as JSON

Section titled “Step 3 — Run experiments described as JSON”
config_text = """
[
{"model": "majority", "params": {}},
{"model": "knn", "params": {"n_neighbors": 1}},
{"model": "knn", "params": {"n_neighbors": 1, "distance": "manhattan"}},
{"model": "knn", "params": {"n_neighbors": 15, "distance": "manhattan"}}
]
"""
for entry in json.loads(config_text):
model = make_model(entry["model"], **entry["params"])
pred = model.fit(X_fit_s, y_fit_c).predict(X_val_s)
print(f"{model!r:<60} validation churn F1 {churn_f1(y_val_c, pred):.3f}")
Output
MajorityClassifier() validation churn F1 0.000
KNNClassifier(n_neighbors=1, distance=Distance.EUCLIDEAN) validation churn F1 0.360
KNNClassifier(n_neighbors=1, distance='manhattan') validation churn F1 0.368
KNNClassifier(n_neighbors=15, distance='manhattan') validation churn F1 0.044

The experiment list is plain text. It could live in a file, come from a web form or be generated by a tuning script. The code never imports or names a model class: it only knows the registry. This is the open/closed principle at the level of a whole program. As in Example 1, the variants compete on the validation part; Example 5 scores the chosen one on the test part, once.

Step 4 — Protect the registry from collisions, not from reruns

Section titled “Step 4 — Protect the registry from collisions, not from reruns”
register("mean")(MeanRegressor) # the same class again: accepted
print("re-registered:", MODELS["mean"].__name__)
Output
re-registered: MeanRegressor
@register("mean")
class MeanRegressor2(MeanRegressor):
"""A second class with a name that is taken."""
Output
ValueError: model name 'mean' is already used by MeanRegressor

Two plugins that claim the same name would silently replace each other. The check turns that into an error at import time, where the cause is clear. The same class may register again: a notebook cell that you run twice, or importlib.reload(), defines the class a second time with the same module and qualified name (__qualname__), and the registry must not reject that.

Common mistakes:

  • Expecting a class to be registered before its module is imported. @register runs when Python executes the class statement. A package therefore imports all its model modules in __init__.py (the mini-project does this), and plugin systems import them through entry points.
  • Writing the factory as an if/elif chain on the name. It works for three models and grows with every new one. The dict lookup never grows.
  • Registering instances instead of classes. MODELS["knn"] = KNNClassifier() hands the same object to every caller, so one experiment’s fit() changes another’s model.

Example 5 — Assemble a pipeline with a builder

Section titled “Example 5 — Assemble a pipeline with a builder”

Goal: Chain a scaler and the chosen KNN model into one object that is fitted once, on the training part only. Assemble it from config entries, with each step checked before training starts.

Step 1 — Put the module 20 Pipeline on the template

Section titled “Step 1 — Put the module 20 Pipeline on the template”
type Step = tuple[str, Any]
def check_steps(steps: Sequence[Step]) -> None:
if not steps:
raise ValueError("a Pipeline needs at least one step")
names = [name for name, _ in steps]
if len(set(names)) != len(names):
raise ValueError(f"step names must be unique, got {names}")
for name, step in steps[:-1]:
if not hasattr(step, "transform"):
raise TypeError(f"step {name!r} must have a transform() method")
class Pipeline(BaseEstimator):
"""Transformers followed by one final estimator (module 20)."""
_requires_y = False # the last step decides whether it needs y
def __init__(self, steps: list[Step]) -> None:
self.steps = steps # stored unchanged, scikit-learn style; fit() validates
@classmethod
def builder(cls) -> "PipelineBuilder":
return PipelineBuilder()
def __repr__(self) -> str:
lines = [f" ({name!r}, {step!r})," for name, step in self.steps]
return "Pipeline([\n" + "\n".join(lines) + "\n])"
def __len__(self) -> int:
return len(self.steps)
def __iter__(self) -> Iterator[Step]:
return iter(self.steps)
def __getitem__(self, key: int | slice | str) -> Any:
if isinstance(key, str):
return dict(self.steps)[key]
if isinstance(key, slice):
return Pipeline(self.steps[key])
return self.steps[key][1]
def _fit(self, X: Rows, y: list | None) -> None:
check_steps(self.steps) # validation at the start of fit()
for _, step in self.steps[:-1]:
X = step.fit(X, y, callbacks=self._callbacks).transform(X)
self[-1].fit(X, y, callbacks=self._callbacks)
def _transform(self, X: Sequence[Row]) -> Any:
for _, step in self.steps[:-1]:
X = step.transform(X)
return X
def predict(self, X: Sequence[Row]) -> list:
return self[-1].predict(self._transform(X))
def score(self, X: Sequence[Row], y: Sequence[Any]) -> float:
return self[-1].score(self._transform(X), y)

The pipeline has the same interface as one model: fit(), predict() and score(). It is a BaseEstimator, so get_params(), == and repr() work on it, and its fit() is the template: the hook _fit() checks the steps first, then passes each transformer’s output to the next step. The callbacks of the pipeline’s fit() reach every step through self._callbacks. As in module 20 and in scikit-learn, __init__ stores steps unchanged and fit() validates them: a constructor that only stores its arguments keeps get_params() and set_params() honest.

class PipelineBuilder:
def __init__(self) -> None:
self._steps: list[Step] = []
def add(self, name: str, step: Any) -> Self:
if not name.isidentifier():
raise ValueError(f"step name {name!r} is not a valid identifier")
if any(existing == name for existing, _ in self._steps):
raise ValueError(f"step {name!r} was already added")
self._steps.append((name, step))
return self # returning self makes the calls chainable
def build(self) -> Pipeline:
check_steps(self._steps) # fail now, not later inside fit()
return Pipeline(list(self._steps))

add() checks the name at once and returns the builder, which allows the fluent chain .add(...).add(...). build() runs the same check_steps() that fit() runs, so a broken pipeline fails before any training starts. A pipeline built without the builder is still checked, in fit().

Step 3 — Build from config entries, train once, test once

Section titled “Step 3 — Build from config entries, train once, test once”
chosen = {"n_neighbors": 1, "distance": "manhattan"} # the best validation F1 above
steps_config = [["scale", "scaler", {}], ["model", "knn", chosen]]
builder = Pipeline.builder()
for step_name, model_name, params in steps_config:
builder.add(step_name, make_model(model_name, **params))
pipe = builder.build()
pipe.fit(X_tr_c, y_tr_c, callbacks=[FitLogger()])
print(pipe)
print(len(pipe), pipe["model"] is pipe[-1], len(pipe[:1]))
print(classification_report(y_te_c, pipe.predict(X_te_c)))
Output
fit Pipeline: 938 rows x 2 features
fit StandardScaler: 938 rows x 2 features
fit KNNClassifier: 938 rows x 2 features
Pipeline([
('scale', StandardScaler(with_mean=True, with_std=True)),
('model', KNNClassifier(n_neighbors=1, distance='manhattan')),
])
2 True 1
precision recall f1 support
0 0.823 0.801 0.812 256
1 0.190 0.214 0.202 56
accuracy 0.696 312
macro avg 0.507 0.508 0.507 312
weighted avg 0.710 0.696 0.702 312

The loop adds one step per config entry: this is where a builder pays off. The settings come from the validation comparison of Example 4. The pipeline is fitted on all 938 training rows and scored on the 312 test rows once; these are exactly the test numbers of the module 21 project. The pipeline cannot leak test data into the scaler, because the only fit() call receives the training rows.

for attempt in (
lambda: (
Pipeline.builder().add("scale", StandardScaler()).add("scale", StandardScaler())
),
lambda: Pipeline.builder().add("my model", LinearRegression()),
lambda: (
Pipeline.builder()
.add("model", LinearRegression())
.add("scale", StandardScaler())
.build()
),
lambda: Pipeline([("model", LinearRegression()), ("scale", StandardScaler())]).fit(
X_tr_h, y_tr_h
),
):
try:
attempt()
except (ValueError, TypeError) as err:
print(f"{type(err).__name__}: {err}")
Output
ValueError: step 'scale' was already added
ValueError: step name 'my model' is not a valid identifier
TypeError: step 'model' must have a transform() method
TypeError: step 'model' must have a transform() method

The first two mistakes fail at the add() call that causes them. The third one, a model before a transformer, fails in build(). The fourth builds the same broken pipeline without the builder: the constructor accepts it, and the template’s fit() rejects it before any step learns.

Common mistakes:

  • Fitting the scaler on all the rows before the split. The test rows then influence the scaling: this is data leakage, and it makes test scores too optimistic. Fit the whole pipeline on the training rows only.
  • Putting the same step object in two pipelines. Fitting one pipeline refits the shared object of the other. Build fresh steps with the factory.
  • Forgetting build(). A PipelineBuilder has no fit(), so the call fails with AttributeError.

Example 6 — Inject a loader and a logger into a data job

Section titled “Example 6 — Inject a loader and a logger into a data job”

Goal: A nightly job reads the customer file, computes the churn rate per contract and logs a line per contract. Make the job testable in milliseconds, without the real file, and run its tests with pytest.

def churn_job_hard_wired() -> None:
with open("data/customers.csv", encoding="utf-8", newline="") as f:
records = list(csv.DictReader(f))
for contract, rate in churn_rate_by(records, "contract").items():
print(f"{contract}: {rate:.1%}")
churn_job_hard_wired()
Output
month-to-month: 29.6%
one-year: 8.8%
two-year: 3.2%

The job works. To test it, you need the 5,000-row file and you must capture what it prints. You cannot test the empty-file case or a file with an unusual contract type without creating files on disk.

Step 2 — Inject the reader and the logger

Section titled “Step 2 — Inject the reader and the logger”
type Reader = Callable[[str], list[dict[str, str]]]
def churn_job(
path: str = "data/customers.csv",
*,
read: Reader = read_csv_records,
log: Callable[[str], None] = print,
) -> dict[str, float]:
records = read(path)
if not records:
raise ValueError(f"{path}: no records")
rates = churn_rate_by(records, "contract")
for contract, rate in rates.items():
log(f"{contract}: {rate:.1%}")
return rates
rates = churn_job()
Output
month-to-month: 29.6%
one-year: 8.8%
two-year: 3.2%

The defaults keep production code as short as before: churn_job() reads the real file and prints. The job also returns the rates, so a test can check numbers instead of parsing text. The keyword-only * forces callers to name the dependencies, which keeps calls readable.

def fake_read(path: str) -> list[dict[str, str]]:
return [
{"contract": "one-year", "churned": "0"},
{"contract": "one-year", "churned": "1"},
{"contract": "two-year", "churned": "0"},
]
logged: list[str] = []
result = churn_job("any.csv", read=fake_read, log=logged.append)
print(result)
print(logged)
assert result == {"one-year": 0.5, "two-year": 0.0}
try:
churn_job("empty.csv", read=lambda path: [])
except ValueError as err:
print("empty file:", err)
Output
{'one-year': 0.5, 'two-year': 0.0}
['one-year: 50.0%', 'two-year: 0.0%']
empty file: empty.csv: no records

fake_read returns three records typed in the test. logged.append collects the log lines. The empty-file case needs one lambda. No file is opened, and the test checks exact values.

Step 4 — Save the job and its tests and run pytest

Section titled “Step 4 — Save the job and its tests and run pytest”
churn_job.py
"""Nightly churn job: churn rate per contract type, with injected I/O."""
import csv
from collections.abc import Callable
type Records = list[dict[str, str]]
def read_csv_records(path: str) -> Records:
with open(path, encoding="utf-8", newline="") as f:
return list(csv.DictReader(f))
def churn_rate_by(records: Records, column: str) -> dict[str, float]:
groups: dict[str, list[int]] = {}
for rec in records:
groups.setdefault(rec[column], []).append(int(rec["churned"]))
return {key: sum(flags) / len(flags) for key, flags in sorted(groups.items())}
def churn_job(
path: str = "data/customers.csv",
*,
read: Callable[[str], Records] = read_csv_records,
log: Callable[[str], None] = print,
) -> dict[str, float]:
records = read(path)
if not records:
raise ValueError(f"{path}: no records")
rates = churn_rate_by(records, "contract")
for contract, rate in rates.items():
log(f"{contract}: {rate:.1%}")
return rates
def main() -> None:
"""The composition root: the real reader and the real logger."""
churn_job()
if __name__ == "__main__":
main()
test_churn_job.py
"""Tests for churn_job.py. They pass fakes, so they never open a file."""
import pytest
from churn_job import churn_job
RECORDS = [
{"contract": "one-year", "churned": "0"},
{"contract": "one-year", "churned": "1"},
{"contract": "two-year", "churned": "0"},
]
def test_rates_per_contract():
rates = churn_job("any.csv", read=lambda path: RECORDS, log=lambda line: None)
assert rates == {"one-year": 0.5, "two-year": 0.0}
def test_one_log_line_per_contract():
lines = []
churn_job("any.csv", read=lambda path: RECORDS, log=lines.append)
assert lines == ["one-year: 50.0%", "two-year: 0.0%"]
def test_job_reads_the_path_it_is_given():
seen = []
def fake_read(path):
seen.append(path)
return RECORDS
churn_job("data/2024-12.csv", read=fake_read, log=lambda line: None)
assert seen == ["data/2024-12.csv"]
def test_empty_file_is_an_error():
with pytest.raises(ValueError, match="empty.csv: no records"):
churn_job("empty.csv", read=lambda path: [])
Terminal
python -m pytest -q test_churn_job.py
python churn_job.py
Output
.... [100%]
4 passed in 0.00s
month-to-month: 29.6%
one-year: 8.8%
two-year: 3.2%

The test file imports the job and passes fakes. All tests run without the real data. The last command is the composition root at work: main() uses the real reader and print.

Common mistakes:

  • Patching the global open or print in tests (with monkeypatch, module 14) when you could pass a parameter. Patching works, but it couples the test to how the job is written inside.
  • Making every dependency a required argument. Callers then must wire everything by hand. Give production defaults.
  • Creating the dependency inside the function “just as a default”: def churn_job(read=None): read = read or read_csv_records works, but read=read_csv_records in the signature says the same thing more clearly.

Example 7 — Cut an over-engineered imputer back to a function

Section titled “Example 7 — Cut an over-engineered imputer back to a function”

Goal: 90 houses in data/houses.csv have no lot_sqft. A colleague wrote a “flexible” design to fill the gaps with the median. Measure what it costs, replace it, and find the case where a class really pays.

An imputer fills missing values with a substitute value, such as the median of the column. Module 26 covers imputation in depth.

Step 1 — Read the over-engineered version

Section titled “Step 1 — Read the over-engineered version”
class ImputationStrategy(ABC):
@abstractmethod
def compute(self, values: list[float]) -> float: ...
class MedianImputationStrategy(ImputationStrategy):
def compute(self, values: list[float]) -> float:
return statistics.median(values)
class ImputerFactory:
_instance = None
def __new__(cls) -> "ImputerFactory": # a singleton
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def create(self, kind: str) -> ImputationStrategy:
if kind == "median":
return MedianImputationStrategy()
raise ValueError(kind)
class ImputationContext:
def __init__(self, strategy: ImputationStrategy) -> None:
self._strategy = strategy
def get_strategy(self) -> ImputationStrategy:
return self._strategy
def impute(self, values: list[float | None]) -> list[float]:
fill = self.get_strategy().compute([v for v in values if v is not None])
return [fill if v is None else v for v in values]
with open("data/houses.csv", encoding="utf-8", newline="") as f:
lots = [float(r["lot_sqft"]) if r["lot_sqft"] else None for r in csv.DictReader(f)]
filled_old = ImputationContext(ImputerFactory().create("median")).impute(lots)
print(f"{lots.count(None)} missing, filled with {filled_old[lots.index(None)]:,.0f}")
Output
90 missing, filled with 7,530

Four classes and about 30 lines do one thing: replace None with the median. There is an abstract base with one subclass, a singleton factory with one branch, a context class with a getter, and no second strategy anywhere. Every reader must open four classes to learn what happens.

def fill_missing(
values: list[float | None], fill: Callable[[list[float]], float] = statistics.median
) -> list[float]:
"""Replace None with fill(the known values)."""
value = fill([v for v in values if v is not None])
return [value if v is None else v for v in values]
filled = fill_missing(lots)
print(filled == filled_old, fill_missing([1.0, None, 5.0], fill=statistics.fmean))
Output
True [1.0, 3.0, 5.0]

Five lines give the same result. The fill parameter is still a strategy, but a strategy is just a function, so it needs no class. When a second need appears, such as filling with the mean, the caller passes statistics.fmean. Nothing else changes.

Step 3 — Use a class when the step learns state

Section titled “Step 3 — Use a class when the step learns state”
@register("median_imputer")
class MedianImputer(TransformerMixin, BaseEstimator):
"""Learn the median of each column in fit(); fill None in transform()."""
def _fit(self, X: Rows, y: list | None) -> None:
columns = list(zip(*X, strict=True))
self.medians_ = [
statistics.median(v for v in col if v is not None) for col in columns
]
def _validate(self, X: Rows, y: list | None) -> tuple[Rows, list | None]:
return [list(row) for row in X], y # allow None: filling it is the job
def _check_input(self, X: Rows) -> Rows:
check_is_fitted(self)
return [list(row) for row in X]
def _transform(self, X: Rows) -> Rows:
return [
[m if v is None else v for v, m in zip(row, self.medians_, strict=True)]
for row in X
]
train_lots, test_lots = lots[:2400], lots[2400:]
imputer = make_model("median_imputer").fit([[v] for v in train_lots])
test_filled = imputer.transform([[v] for v in test_lots])
print(f"train median {imputer.medians_[0]:,.0f}; test gaps {test_lots.count(None)}")
print("first test gap ->", test_filled[test_lots.index(None)])
Output
train median 7,490; test gaps 23
first test gap -> [7490.0]

A model must learn the median from the training rows and reuse it on the test rows, which may be one row at a time in production. Now there is state that lives between two calls, so a class is the right tool. The class reuses the template and the registry, and it overrides the validation hooks, because None is valid input for an imputer. The rule: a function when the job is done in one call; a class when it learns something that later calls need.

Common mistakes:

  • Adding a pattern “for later”. YAGNI: later, you will know what really varies, and the design will fit it better.
  • Removing a pattern that does pay. The registry in Example 4 has several real entries and a config that uses them. Judge by the needs you have, not by a rule.
  • Computing the median on all rows before the split. As with scaling, that leaks test data into training.
Mistake Symptom Fix
A class that loads, computes and formats Tests need real files; a format change breaks the numbers Split by reason to change (SRP)
An if/elif chain on a type name Every new option edits tested code A dict of functions or classes, or pass the function (OCP)
A subclass that changes what score() means Model selection silently picks the wrong model Keep the meaning; pass another metric in (LSP)
A fat ABC Subclasses implement methods only to raise NotImplementedError Several small Protocols (ISP)
High-level code that opens files and prints Cannot run on other data or test without the file Inject a reader and a log function (DIP)
distance=manhattan() TypeError: manhattan() missing 2 required positional arguments Pass the function: distance=manhattan
Strategy resolved in __init__ set_params(distance=...) has no effect Store the setting; resolve it in fit()
Settings chosen by their test score The reported test score is too optimistic Choose on a validation part or with cross-validation; test once
A duplicate-name check that also rejects the same class A rerun notebook cell or importlib.reload() raises “already used” Accept a class with the same __module__ and __qualname__
A subclass overrides the template fit() Its input checks and callbacks disappear Override the hook _fit()
A class used before its module is imported make_model() says “unknown model” Import every model module in the package __init__.py
One estimator instance in the registry or in two pipelines Fitting one experiment changes another Register classes; let the factory build fresh objects
A callback that keeps state between trainings The second training stops at once Reset the state in on_fit_start
Fitting the scaler before the split Test scores too optimistic (data leakage) Fit the pipeline on the training rows only
A pattern with one implementation Many classes, one behavior A function; add the pattern when the second need appears
  • Web frameworks: Flask’s @app.route("/orders") registers a function in a URL registry (factory and registry). Django class-based views are template methods with hooks such as get_queryset(). Middleware is a pipeline, and FastAPI’s Depends injects database sessions.
  • Plugin systems: pytest finds plugins through entry points and calls their hook functions, such as pytest_collection_modifyitems (registry and observer). Installers read the console_scripts entry points to create terminal commands, and editors load extensions through similar registries.
  • GUIs and events: a Tkinter button calls its command= function on each click, and Qt connects signals to slots. Both are the observer pattern, as are browser event listeners.
  • Tooling: the logging module sends one record to many handlers (observer), each with a Formatter (strategy). sorted(key=...) and re.sub(pattern, function, text) take strategies.
  • Good design means low coupling (parts know little about each other) and high cohesion (each unit has one job).
  • SOLID: one reason to change per unit; extend by adding code; subclasses keep their parent’s promises; small interfaces; depend on abstractions, not on files and print().
  • Strategy: pass the algorithm in. In Python, a strategy is usually a function; use a callable object when it has settings.
  • Factory and registry: a dict maps names to classes, a decorator fills it, and make_model(name, **params) builds fresh objects from config text.
  • Template method: the base class fixes the steps (fit() validates, notifies, calls _fit()), and subclasses write only the hook.
  • Observer: the subject calls every callback at each event. Callbacks can record, print or stop training without changes to the loop.
  • Pipeline chains steps with one interface. A builder assembles an object step by step and checks each step; in Python, keyword arguments often replace it.
  • Dependency injection passes collaborators in, with production defaults. Tests pass fakes and run without files.
  • YAGNI: add a pattern when a real need appears. A function is often enough; a class is for state that lives between calls.

Q1. What do coupling and cohesion measure, and which direction should each go?

Answer

Coupling measures how much one part depends on the details of another; keep it low, so that you can change one part alone. Cohesion measures how closely the contents of one unit belong together; keep it high, so that each unit has one job.

Q2. ChurnReport.run() reads a CSV file, computes churn rates and formats text. Which principle does it break, and how do you fix it?

Answer

The single responsibility principle: it has three reasons to change (the source, the metric and the format). Split it into three functions, such as read_csv_records(), churn_rate_by() and format_rates(). Each one can then change and be tested alone.

Q3. A subclass of MeanRegressor returns the MSE from score(). Nothing crashes. What goes wrong, and which principle is broken?

Answer

Code such as max(models, key=score) assumes that higher is better. A large MSE then looks like the best score, so the worst model wins, silently. This breaks the Liskov substitution principle: the subclass changes the meaning of an inherited method. Keep score() as “higher is better” and pass other metrics in, or negate them as neg_mean_squared_error does.

Q4. Why is KNNClassifier(distance=manhattan) better than an if kind == "manhattan" branch inside the model?

Answer

The model calls whatever function it receives, so a new distance is a new function and the model never changes (open/closed principle). Each strategy can be tested alone, and the caller can even pass a distance that the model’s author never imagined, such as a weighted one.

Q5. Why does KNNClassifier.__init__ store distance unchanged and resolve it in fit()?

Answer

So that get_params(), set_params(), repr() and equality work with the setting the user gave. If __init__ resolved the name into a function, set_params(distance="chebyshev") would change the attribute but not the function in use. This is the scikit-learn convention.

Q6. In the template method fit(), which part does the base class own and which part does the subclass write? What breaks if a subclass overrides fit()?

Answer

The base class owns the steps and their order: validate the input, notify the callbacks, call the hook, record n_features_in_, notify again, return self. The subclass writes only the hook _fit(). A subclass that overrides fit() loses the validation and the callbacks, so it behaves differently from every other model.

Q7. How does an EarlyStopping observer stop a training loop that does not know about it?

Answer

The loop checks one agreed flag, model.stop_training, after it notifies the callbacks. The observer receives the model in on_epoch_end and sets the flag to True when the loss stops improving. The loop knows only the flag, not the stopping rule.

Q8. make_model("knn") raises “unknown model ‘knn’” in a new script, although KNNClassifier has @register("knn"). What is the likely cause?

Answer

The module that defines KNNClassifier was never imported, so its class statement, and with it the decorator, never ran. Import the model modules in the package’s __init__.py, or import the module before you call the factory.

Q9. Give two forms of dependency injection, and explain why they make a job easy to test.

Answer

A parameter with a production default, such as churn_job(read=read_csv_records, log=print), and a constructor argument, such as FitLogger(log=lines.append). A test passes a fake reader that returns records typed in the test and a list’s append as the logger. It then runs in milliseconds, without files, and checks exact values.

Q10. When is a builder worth it in Python, and what usually replaces it?

Answer

When an object is assembled in steps, for example in a loop over config entries or with optional steps, and each step should be checked as it arrives. For an object with a few settings, keyword arguments with defaults or a dataclass are clearer.

Q11. A colleague wraps one median calculation in an abstract strategy, a singleton factory and a context class. What do you suggest, and when would a class be the right choice?

Answer

Replace it with a function that takes the fill function as a parameter (YAGNI, KISS). A class is right when the step learns state in one call and uses it in later calls, such as an imputer that learns the median on the training rows and fills the test rows.

Your progress

0 / 4 done

  • Exercises: 27 exercises on SOLID, strategy, factories, template methods, observers, builders, dependency injection and refactoring, with hints and full solutions.
  • Mini-project: assemble the full minilearn package and run it end to end on churn and house prices.
  • Cheat sheet: every principle and pattern of this module, with its Python form and its smells.
  • Part 3 checkpoint: mixed exercises across modules 18 to 22 and a self-assessment rubric.
  • Next module: 23. NumPy starts Part 4. NumPy arrays replace the lists of lists of minilearn and make the same calculations fast.