Concept Explanation
The Gang of Four book is about object-oriented solutions. Python is not purely object-oriented, and in many cases a built-in feature — a generator, a with block, a dict — does the job the book says needs a strategy, an iterator, or a factory.
This lesson is the counterweight. Not "never use design patterns", but "reach for the Pythonic tool first; reach for the pattern when its problem is really there."
The Pattern That Vanishes: Strategy Becomes a Function
# OO way: an interface, a bunch of classes, a strategy.
# Pythonic way: pass a callable.
def apply_discount(amount, strategy):
return strategy(amount)
def ten_percent(x):
return x * 0.9
apply_discount(100, ten_percent)
Functions are first-class. Where the book introduces a class hierarchy to swap algorithms, Python can often just take a function argument.
Iterator Becomes a Generator
The Iterator pattern lets you traverse a collection without exposing its internals. Python's for loop and generators already give you this:
def squares_up_to(n):
for i in range(n):
yield i * i
for s in squares_up_to(5):
print(s)
Factory Becomes a Classmethod, or Just a Function
class MyClass:
@classmethod
def from_csv(cls, path): ...
@classmethod
def from_dict(cls, data): ...
The Patterns Worth Keeping
Some patterns remain valuable in Python because they are about structure, not language features:
| Pattern | Why it still earns its keep in Python |
|---|---|
| Adapter | Bridges a third-party API and your code's shape |
| Facade | Simplifies a complex subsystem behind one function |
| Observer | Event systems, requests, and subscriptions are still hard |
| Repository | Data-access layer boundary |
| MVC / MVVM | UI and domain separation |
| Dependency injection | Testability, not magic |
Protocols and Duck Typing Replace Interface
typing.Protocol (PEP 544) models "if it quacks, it counts" without inheritance. @runtime_checkable lets you use it in isinstance.
singledispatch: The Pythonic Visitor/Overload
from functools import singledispatch
@singledispatch
def render(data): ...
@render.register
def _(data: dict): ...
@render.register
def _(data: list): ...
Composition Over Inheritance
Python makes composition natural: class Order: that has a Customer, rather than class Order(Customer). The more you try to make Python look like Java, the more friction you create. The idiomatic code is usually the simpler one.
Code Example #1 (Basic)
Where a pattern collapses and where it still earns its keep.
from dataclasses import dataclass
from functools import singledispatch
# --- Strategy as a callable, not a class hierarchy ---
def flat_shipping(weight):
return 5.0
def weight_shipping(weight):
return 2.0 + weight * 0.5
def price_order(subtotal, weight, shipping_fn):
return subtotal + shipping_fn(weight)
print("Strategy as a function:")
print(f" flat: {price_order(100, 3, flat_shipping)}")
print(f" weight: {price_order(100, 3, weight_shipping)}")
# --- Factory as a classmethod ---
@dataclass
class Point:
x: float
y: float
@classmethod
def from_degrees(cls, lat, lon):
# imagine a conversion -- here just storing them
return cls(lon, lat)
@classmethod
def from_tuple(cls, t):
return cls(*t)
print("\nFactory as a classmethod:")
print(f" {Point.from_tuple((3, 4))}")
print(f" {Point.from_degrees(50.0, 8.0)}")
# --- The singleton Python already gives you ---
print("\nA module is a singleton: import it once, share everything.")
# --- singledispatch as the pattern that replaces a visitor ---
@singledispatch
def render(data):
return f"unknown: {data!r}"
@render.register
def _(data: dict):
return "a dict"
@render.register
def _(data: list):
return f"a list of {len(data)}"
@render.register
def _(data: Point):
return f"Point({data.x}, {data.y})"
print("\nsingledispatch (the Pythonic visitor):")
for value in [{"name": "x"}, [1, 2, 3], Point(1.0, 2.0), "hi"]:
print(f" {value!r:22} -> {render(value)}")
# --- Composition over inheritance ---
@dataclass
class Address:
city: str
country: str
@dataclass
class Customer:
name: str
address: Address # HAS A, not IS A
c = Customer("Ada", Address("London", "UK"))
print(f"\nComposition: {c.name} lives in {c.address.city}")
# --- A real Pattern that is still useful: Adapter ---
class ThirdPartyAPI:
def fetch(self, id_str):
return f"legacy-{id_str}"
class OurInterface:
def get(self, key):
raise NotImplementedError
class LegacyAdapter(OurInterface):
def __init__(self, legacy: ThirdPartyAPI):
self.legacy = legacy
def get(self, key):
return self.legacy.fetch(str(key))
adapter = LegacyAdapter(ThirdPartyAPI())
print(f"\nAdapter: our get(42) -> {adapter.get(42)!r} via the legacy fetch()")
print(" The Adapter pattern survives in Python because the mismatch is between")
print(" two APIs you do not control -- no language feature fixes that for you.")
The pattern's value is not that it appears in the code, but that the code is simpler because it took the Pythonic path. Strategy as a callable is one line instead of an abstract class plus two subclasses.
Code Example #2 (Intermediate)
A Protocol for duck typing, singledispatch for type-based logic, and the small idioms that quietly replace whole chapters of pattern boilerplate.
from functools import singledispatch
from typing import Protocol, runtime_checkable
# ---------- Protocol: an interface without inheritance ----------
@runtime_checkable
class Drawable(Protocol):
def draw(self) -> None: ...
class Circle:
def __init__(self, r):
self.r = r
def draw(self):
print(f" circle r={self.r}")
class Square:
def __init__(self, side):
self.side = side
def draw(self):
print(f" square side={self.side}")
class Ghost:
pass # no draw() method
print("Protocol (structural) typing:")
for shape in [Circle(2), Square(3)]:
print(f" {type(shape).__name__} is Drawable: {isinstance(shape, Drawable)}")
shape.draw()
print(f" Ghost is Drawable: {isinstance(Ghost(), Drawable)}")
print(" Neither Circle nor Square inherits Drawable -- having draw() is enough.")
# ---------- singledispatch for format-by-type ----------
@singledispatch
def describe(value):
return f"an unknown {type(value).__name__}"
@describe.register
def _(value: int):
return "an integer"
@describe.register
def _(value: float):
return "a float"
@describe.register
def _(value: list):
return f"a list of {len(value)} items"
@describe.register
def _(value: dict):
return f"a dict with keys {sorted(value)}"
print("\nsingledispatch:")
for v in [1, 2.5, [1, 2, 3], {"a": 1}, "hi"]:
print(f" {v!r:20} -> {describe(v)}")
# ---------- Try/except as a pattern: EAFP over LBYL ----------
print("\nEAFP (Easier to Ask Forgiveness than Permission):")
def parser(value):
try:
return {"number": int(value)}
except ValueError:
return {"text": value}
print(f" '42' -> {parser('42')}")
print(f" 'hello' -> {parser('hello')}")
# ---------- Data passing with immutable defaults ----------
print("\nMutable default pitfall:")
def append_bad(item, bucket=[]): # BAD: shared across calls
bucket.append(item)
return bucket
def append_good(item, bucket=None): # GOOD: new list per call
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(f" bad: {append_bad(1)} then {append_bad(2)} <- shared!")
print(f" good: {append_good(1)} then {append_good(2)} <- fresh\n")
# ---------- Enum as a labelled constant ----------
from enum import Enum
class Status(Enum):
PENDING = "pending"
PAID = "paid"
SHIPPED = "shipped"
print("Enum:", [s.value for s in Status])
print(f" matching: {Status.SHIPPED.value}")
These idioms (Protocol, singledispatch, EAFP, dataclass, Enum) are what a lot of "design pattern" boilerplate turns into in Python. They are not inferior versions; they are the point.
Common Mistakes
- Forcing a GoF pattern where a built-in does the job: a strategy where a callable works, an iterator where a generator works.
- Using
isinstancein a type-dispatch chain whensingledispatchfits better. - Building a class hierarchy to share one method: prefer a mixin or composition, or a plain function.
- Comparing an
Enummember to its raw value:Status.PAID == "paid"isFalsefor a plainEnum. Compare members withis, or subclassstr, Enumif you want value equality. - The mutable-default-argument bug, which trips people who think in "patterns" and reach for a default list.
LBYL(look before you leap) whereEAFPis cleaner;try/exceptis a pattern in Python, not just an error handler.- Over-abstracting a small script with a factory when a function is enough.
- Using inheritance when you only need composition:
class Order(Customer)is a modelling error. - Using
@staticmethodwhere a@classmethodor a plain function is natural: the pattern can hide real intent. - Writing a
Visitorwhensingledispatchis what the problem needs. - Treating a decorator as an inheritance substitute: use a context manager for lifecycle, a decorator for wrapping, and a class for structure.
- Calling a Protocol without
runtime_checkablethen expectingisinstanceto work:typing.Protocolis not for runtime checks by default.
Best Practices
- Reach for the language feature first — generators, callables, contexts, dicts — and only add a class hierarchy when the problem truly needs it.
- Prefer composition over inheritance.
- Use
@dataclass,Enum, andProtocolto express structure rather than boilerplate. - Use
singledispatchfor type-based dispatch. - Prefer
EAFPfor normal flow — it is often clearer and often the intended idiom. - Keep a pattern only where it adds a boundary — adapters, facades, repositories, observers — not where a callable or dict does the job.
- Name things plainly; a pattern can live in a function, not a class.
- *Teach the pattern's why, not its shape.*
- Return
Nonefor "not found" or use aOptional; don't force a heavy pattern to handle a missing value. - Use
functools.wrapsif you wrap anything, even a plain callable. - Don't add a
ContextManagerwhen awitharound a built-in or a library function already works. - Use
dataclassinstead of a hand-written__init__,__eq__, and__repr__.
Practice Exercises
- The Collapsing Strategy: Rewrite a
ShippingStrategy(class hierarchy with two subclasses) as a function argument. Show both and comment on the "One interface, many classes" reduction. - singledispatch: Write a
describefunction that handlesint,str,list, anddict, using@singledispatchplus@describe.register, and give it a fallback. - Composition: Create an
Orderthat has aCustomerand has anAddress, and aPaymentMethodwith apay()method. Include a comment on why this is better than inheritance here.