Prerequisites
- !Classes, modules, and module-level state
- !First-class functions and decorators
What You'll Learn
- 1Recognise a recurring design problem by its symptoms
- 2Implement singleton, factory, observer, and strategy in idiomatic Python
- 3State the failure mode of each pattern
- 4Identify patterns that Python's own features replace
- 5Decide when a simpler mechanism solves the same problem
Design patterns are answers to problems you have already felt, and their value lies in the shared vocabulary rather than in code you should paste. Python also shapes them differently than languages without first-class functions or module singletons: several classical patterns collapse into a function argument, a module, or a context manager, and forcing the textbook version produces ceremony that obscures intent. The four below are the ones that still pay rent, along with the reasons to reach past them.
Symptoms before solutions
Start from the shape of the problem, not from the pattern's name. The table maps the complaints you actually hear in code review to the structural response.
| Symptom in the code | Underlying problem | Candidate response |
|---|---|---|
| Long if and elif chain on a mode or type | Behaviour varies by a value | Strategy or dispatch table |
| Construction logic scattered across call sites | Creation rules duplicated | Factory |
| Object must notify several others of a change | Components tightly coupled | Observer |
| Exactly one shared instance is required globally | Shared configuration or connection | Module state, or singleton as last resort |
| Class only differs in a few steps of an algorithm | Subclass explosion | Template method or strategy |
Asking which row you are in saves you from implementing a pattern for a problem it does not address. Notice also how often the answer is a function argument rather than a new class hierarchy, which is the specific flavour of Python's take on these ideas.
Singleton: usually a module already is one
The classical singleton guards a single instance behind a factory. In Python, a module is imported once per process, so module-level state gives you exactly that guarantee with no machinery, and it is the correct default. A class-based singleton is justified only when you need the construction protocol, subclass control, or laziness that a module import does not provide.
class Database:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self, dsn="memory://"):
if getattr(self, "_initialised", False):
return
self.dsn = dsn
self._initialised = True
def query(self, sql):
return f"{self.dsn} :: {sql}"
first = Database("postgres://primary")
second = Database("postgres://replica")
print(first is second) # True
print(second.dsn) # postgres://primary
print(first.query("select 1")) # postgres://primary :: select 1
The guard inside __init__ is essential: Python calls __init__ on every construction, even when __new__ returned the existing object, so without the flag each call would overwrite the shared state and the singleton would appear broken in the most confusing way. The costs are real, though: global state complicates tests, makes concurrent configuration order matter, and hides dependencies. Prefer dependency injection and reach for a singleton only when an external resource genuinely must exist once.
Factory: one place that decides what to build
A factory concentrates construction rules so callers describe intent rather than classes. It earns its keep when the choice depends on configuration, when construction is expensive and should be cached, or when the concrete type should stay hidden behind an interface.
from dataclasses import dataclass
@dataclass(frozen=True)
class CsvSource:
path: str
def read(self):
return f"csv rows from {self.path}"
@dataclass(frozen=True)
class ApiSource:
url: str
def read(self):
return f"json from {self.url}"
class SourceFactory:
registry = {"csv": CsvSource, "api": ApiSource}
@classmethod
def create(cls, spec):
kind, _, location = spec.partition(":")
source_cls = cls.registry.get(kind)
if source_cls is None:
raise ValueError(f"unknown source kind: {kind}")
return source_cls(location)
source = SourceFactory.create("csv:data/sales.csv")
print(source.read()) # csv rows from data/sales.csv
print(SourceFactory.create("api:https://example.com").read())
The registry turns the factory into an extension point: plugins register their kind at import time and callers never learn the concrete classes. Keep the registry a class attribute rather than a mutable module global, and raise a specific error for unknown kinds so misconfiguration fails at the boundary rather than later with an attribute error. If the factory grows branches that each do substantial work, split it into per-kind builder functions and let the registry map to those instead.
Observer: notifying without knowing
The observer pattern lets a subject publish changes to any number of listeners without holding concrete references to them. It underpins event systems, UI bindings, and reactive pipelines, and the Python version is short because callables are just values.
class EventHub:
def __init__(self):
self._subscribers = {}
def subscribe(self, topic, callback):
self._subscribers.setdefault(topic, []).append(callback)
return lambda: self.unsubscribe(topic, callback)
def unsubscribe(self, topic, callback):
subscribers = self._subscribers.get(topic, [])
if callback in subscribers:
subscribers.remove(callback)
def publish(self, topic, payload):
for callback in list(self._subscribers.get(topic, [])):
callback(payload)
hub = EventHub()
seen = []
unsubscribe = hub.subscribe("order.created", seen.append)
hub.publish("order.created", {"id": 1})
unsubscribe()
hub.publish("order.created", {"id": 2})
print(seen) # [{'id': 1}]
Three details separate a usable hub from a toy. Publish iterates over a copy so a listener that unsubscribes during notification does not skip the next one. Subscribe returns an unsubscribe function, which makes cleanup natural inside a context manager. And exceptions in one listener should be caught and logged rather than allowed to abort the whole notification, otherwise one broken subscriber silences the rest. Watch for reference cycles too: a listener that captures the subject keeps it alive, which matters in long-running processes.
Strategy: behaviour as a constructor argument
Strategy replaces a conditional that selects an algorithm with an object or function chosen once. The payoff shows up in testing, since each behaviour can be exercised alone, and in extension, since adding a mode no longer means editing a shared branch.
class FullTotal:
def compute(self, prices):
return sum(prices)
class DiscountedTotal:
def __init__(self, rate):
self.rate = rate
def compute(self, prices):
return sum(prices) * (1 - self.rate)
class CappedTotal:
def __init__(self, limit):
self.limit = limit
def compute(self, prices):
return min(sum(prices), self.limit)
def checkout(prices, strategy=None):
strategy = strategy or FullTotal()
return round(strategy.compute(prices), 2)
print(checkout([10, 20, 30])) # 60
print(checkout([10, 20, 30], DiscountedTotal(0.1))) # 54
print(checkout([10, 20, 30], CappedTotal(25))) # 25
Because a strategy is plain data about behaviour, it can be selected from configuration, built by a factory, or faked in a test with a two-line class. If every strategy shares the same signature, consider a protocol type hint so static checkers validate call sites, and keep the default strategy obvious in the signature rather than buried inside the body.
What Python makes obsolete
Several GoF patterns exist mainly to compensate for missing language features. A command object with an execute method is usually a callable with its arguments, often partially applied. A builder is frequently a keyword-only constructor or a dataclass with sensible defaults. A decorator wrapping a component is what Python's own decorators already do. The iterator pattern is the for loop, and the template method often reduces to passing a function into a base implementation.
Recognising these collapses matters because the pattern-name version tends to grow: an interface, a concrete class, and a factory to wire them, where a function would have done. Reach for the language first and the catalogue second, and keep the pattern only when it survives the question of whether anyone could read this without knowing the name.
Testing the shapes, not the names
Patterns earn their keep if they make tests simpler, so verify that claim. A strategy should be testable by constructing it alone with no subject. An observer's listeners should be assertable as plain recorded calls, and unsubscribe should be verifiable by publishing again after cleanup. A factory should have a test for the happy path, one per registered kind, and one for an unknown kind asserting a clear error.
If a pattern makes those tests require more setup than the feature itself, the abstraction is working against you. The goal is code where the interesting behaviour is easy to reach and the wiring is boring, and boring wiring is exactly what a well-chosen pattern provides.
Common Mistakes
Forcing a textbook pattern where a function argument would do
Fix: Ask whether a callable parameter solves it; keep the pattern only when it adds a real extension point.
Implementing a singleton without guarding __init__
Fix: Skip re-initialisation on subsequent constructions so shared state is not silently reset.
Notifying observers while iterating the live subscriber list
Fix: Iterate over a copy so listeners can unsubscribe during notification without skipping others.
Letting one observer's exception abort the whole notification
Fix: Catch and log listener errors so a single failure cannot silence the remaining subscribers.
Best Practices
- Name the problem in the code before choosing the pattern
- Prefer module state over a class-based singleton for genuinely shared resources
- Return an unsubscribe handle from subscription APIs
- Type strategy interfaces with a Protocol so call sites are checked
- Write a test for every registered factory kind and for the unknown case
Key Takeaways
- Patterns are vocabulary for recurring problems, not code to apply by default
- Python modules already behave like singletons, which removes most reasons for the class version
- Factories centralise construction and double as plugin registries
- Observers need copy-on-notify, cleanup handles, and isolated error handling
- Strategies turn conditional behaviour into objects that are easy to test and extend