Decorator pattern
The decorator pattern wraps an object with another object that implements the same interface and adds behaviour before or after delegating. It is composition, and it is related to — but not the same as — Python @ function decorators.
Detailed Explanation
You have a Repository that loads a user. You want caching, then logging, then a retry, without editing the repository class. Each wrapper takes a repository, implements get, and calls the inner get. You stack them: LoggingRepo(CachingRepo(SqlRepo())). Callers still see get. That is the decorator pattern.
Python's @decorator syntax wraps functions. It is the same idea at function grain. A class decorator wraps a class object. This glossary page is the object-oriented wrapper: an instance that holds an instance.
The wrapper must keep the contract. If get can raise KeyError, the wrapper should not swallow it unless that is the added behaviour. If get is a coroutine, the wrapper must be async too. functools.wraps applies to function decorators; for class wrappers, implement the same methods and document any extra ones.
Wrappers that add state (a cache dict) need a lifecycle: clear on test teardown, bound the size, consider threads. Wrappers that add I/O (metrics) must not fail the inner call if the metric backend is down, or they become a new source of outages.
Do not confuse this with @property or with mixin inheritance. A mixin adds methods to the class. A decorator object wraps one instance and can be applied selectively. You can wrap a fake in a test with the real cache wrapper and test the cache alone.
Too many wrappers make stack traces long. Three is a lot. If you need ten, you probably want middleware as a list the core loops over, which is the same pattern with a flatter object graph.
Code Examples
class Repo:
def __init__(self) -> None:
self._data = {"ada": 1}
def get(self, name: str) -> int:
return self._data[name]
class CachingRepo:
def __init__(self, inner: Repo):
self.inner = inner
self.cache: dict[str, int] = {}
def get(self, name: str) -> int:
if name not in self.cache:
self.cache[name] = self.inner.get(name)
return self.cache[name]
repo = CachingRepo(Repo())
print(repo.get("ada"), repo.cache) # 1 {'ada': 1}# Function-level cousin:
def traced(fn):
def wrapper(*args, **kwargs):
result = fn(*args, **kwargs)
return result
return wrapperCommon Gotchas
Changing the return type or exception set
callers cannot treat the wrapper as the inner object. Keep the contract.
Unbounded caches in a decorator
memory grows until you evict. Set a max size.
Wrapping a sync object with async or the reverse
the interface changed. Match the inner.
`@` on functions is this pattern for callables
see the fundamentals decorator entry for `wraps` and parameterized decorators.