Design Patterns
Python idioms often replace classical GoF patterns. Factory, Strategy, Observer, and Composite are common; many are naturally expressible with first-class functions.
Python idioms often replace classical GoF patterns. Factory, Strategy, Observer, and Composite are common; many are naturally expressible with first-class functions.
# Strategy pattern via callables
def apply(data, strategy):
return strategy(data)
result = apply([3, 1, 2], sorted) # list sort strategy
result = apply([3, 1, 2], lambda x: sorted(x, reverse=True)) # reversed
# Observer via list of callbacks
class EventEmitter:
def __init__(self): self._handlers = {}
def on(self, event, fn): self._handlers.setdefault(event, []).append(fn)
def emit(self, event, *args): [f(*args) for f in self._handlers.get(event, [])]
Python first-class functions make many GoF patterns unnecessary — prefer simple callables over class hierarchies.