Design Patterns — Fast Recall (Python)
Decorator — add behavior by wrapping
- What: wrap an object/function to add responsibilities without changing it or subclassing.
- Why / when: stack optional features — logging, caching, auth, retry — that you can mix and match at runtime.
- Python truth: this is built into the language as `@decorator` syntax — the most-used pattern you already use daily.
- Don't confuse: GoF Decorator = *wrap an object with same interface*; Python `@` = *wrap a function*. Same idea, both are 'transparent wrapping'.
1def timed(fn): # decorator adds timing
2 def wrapper(*a, **k):
3 print("start"); r = fn(*a, **k); print("end")
4 return r
5 return wrapper
6
7@timed
8def work(): print("working")
9
10work() # start / working / end