Design Patterns in Python


Design Patterns in Python

Simon
I keep hearing people say that design patterns from the Gang of Four book are obsolete, especially in Python. The argument is that you can just use functions instead of classes and get simpler code.

Anna
Right, I've heard that too. And sure, functions can often replace the class-based implementations. But I don't think that makes the patterns themselves obsolete. The real value is in recognizing the type of problem you're dealing with.

Simon
Exactly. Take the Strategy pattern. In the classic object-oriented version, you have an abstract strategy class, concrete subclasses for different algorithms, and a context class that uses the strategy. But in Python, you can just pass a function as an argument.

Anna
And that gives you way less code. The same behavioral decoupling without the boilerplate. The core idea—being able to swap algorithms without the client knowing—is what matters, not the class structure.

Simon
Same with the Observer pattern. Normally you'd have an abstract observer class with an update method, concrete observers, and a subject that maintains a list. But you can just use a list of functions.

Anna
So instead of attaching observer objects, you pass a list of callables to a notify function. That's decoupling without the overhead. And you can even go further by combining data structures like dictionaries mapping events to listeners.

Simon
Then there's the Template Method pattern. The classic version uses an abstract base class with a template method that calls abstract operations and optional hooks. Subclasses implement the required parts. But you can do it functionally.

Anna
You just define a template function that takes the required operations as arguments, with optional hooks as default parameters. That gives you the same structure with about 20 fewer lines of code.

Simon
And you can spice it up by returning a function from a function—like a closure that captures the operations, so you only pass the hooks later. Or use `functools.partial` to pre-fill arguments.

Anna
Both approaches give you the same flexibility as inheritance, but with less ceremony. So while the implementation changes, the pattern—the problem category—remains constant.

Simon
That's the key takeaway: design patterns are about recognizing problem classes like 'I need to swap algorithms' or 'I need to notify multiple listeners without coupling.' How you implement it—classes, functions, or a mix—is secondary.

Anna
So don't throw out the design patterns book. Instead, learn the problems it describes, and then choose the best tools in your language to solve them. In Python, functions are often a great choice, but the pattern knowledge is what makes you a better developer.

Ask anything
We've read this whole study set, so questions about it get the best answers.