Python Decorators: Stacking, Classes, and Validation
A decorator is an ordinary callable that receives a function and returns something callable in its place â and every advanced technique follows from that definition. Stacking layers behaviour in a defined order, class-based decorators keep per-decorator state without nesting three closures, and decorating methods requires knowing that @decorator sits underneath @staticmethod and @classmethod rather than beside them. The failure modes are equally simple to name: lost metadata, reversed order assumptions, and wrappers that break introspection for every framework that reads a signature.
What You'll Learn
- 1Explain the decoration sequence and stacking direction precisely
- 2Preserve name, docstring, and signature with functools.wraps
- 3Write class-based and stateful decorators for repeated use
- 4Place decorators correctly on methods and classes without surprises
Anatomy: what @decorator actually does
@decorator on a function is sugar for rebinding the name: the function object is created, passed to the decorator, and the name is rebound to whatever comes back. Nothing special happens at definition time beyond that call, which means a decorator can rename, wrap, replace, or return the original untouched. The decorator's return value is what all future calls go through, so returning None by mistake turns the decorated function into a callable that raises AttributeError on every use.
The one obligation that separates clean decorators from problematic ones is metadata. Without functools.wraps, the wrapper reports its own __name__, __doc__, and __module__, and â more damaging â its own __wrapped__-less signature, so anything using inspect.signature sees (*args, **kwargs) instead of the real parameters. Frameworks that validate parameters, generate documentation, or build CLI parsers from signatures all break in ways that look unrelated to the decorator that caused them.
import functools
import inspect
def logged(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__} with {len(args)} args")
return func(*args, **kwargs)
return wrapper
@logged
def transfer(amount, currency="USD"):
"""Move money between accounts."""
return f"{amount} {currency}"
print(transfer.__name__) # transfer (not 'wrapper')
print(transfer.__doc__) # Move money between accounts.
print(inspect.signature(transfer)) # (amount, currency='USD')
print(inspect.unwrap(transfer) is transfer.__wrapped__) # True
print(transfer(25)) # calls wrapper, returns '25 USD'
functools.wraps also sets __wrapped__, which lets inspect.unwrap recover the original function â the escape hatch used by test runners and debuggers. If a decorator must preserve the signature exactly, copying the wrapped function's signature onto the wrapper with functools.update_wrapper is the baseline; for full fidelity in argument validation, inspect.signature(func) plus delegation to func is the fallback.
Stacking order, read correctly
Decorators apply bottom up: the function is created, the lowest decorator wraps it, the next one wraps that result, and so on. Reading a stack as a sequence of layers â outermost runs first, innermost runs closest to the original â removes most confusion. The practical consequence is that timing and logging decorators placed above a retry decorator measure the whole retry loop, while the same decorators placed below it measure each individual attempt.
Neither placement is wrong; they answer different questions. Measure total latency from the outside, measure per-attempt latency from the inside. What matters is knowing which number you are reporting, because an average that silently includes retries will look terrible and send an engineer hunting for a performance bug that does not exist.
import functools
import time
def outer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("outer: before")
result = func(*args, **kwargs)
print("outer: after")
return result
return wrapper
def inner(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(" inner: before")
return func(*args, **kwargs)
return wrapper
@outer
@inner
def work():
print(" body")
work()
# outer: before
# inner: before
# body
def retrying(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(3):
try:
return func(*args, **kwargs)
except ConnectionError:
print(f"attempt {attempt + 1} failed")
raise ConnectionError("exhausted")
return wrapper
def traced_attempts(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
print(f"total {time.perf_counter() - start:.4f}s")
return wrapper
@traced_attempts
@retrying
def ping():
print("ping body")
raise ConnectionError("down")
try:
ping()
except ConnectionError:
print("gave up")
# the timer wraps the whole retry loop, so it reports aggregate latency
The last stack answers a specific question: how long did the caller wait, retries included. Move @traced_attempts below @retrying and the same timer instead reports each attempt separately. Both numbers are useful; the mistake is reporting one while believing you measured the other.
Class-based decorators and per-instance state
When a decorator needs configuration, mutable state, or several cooperating methods, a class is cleaner than a closure pyramid. The rule is small: give the class an __init__ that accepts the configuration or the function, and an __call__ that performs the wrapped invocation. Whether the class receives the function at decoration time or at call time determines which shape you write, and both appear in real codebases.
The state advantage is the reason to switch. A closure keeps state in a cell reachable from one wrapper; a class keeps it in attributes, which can be reset, inspected, serialised, and shared across instances through class-level storage. Registration counters, circuit breakers, and rate limiters all need that visibility, and a test can assert on decorator_instance.calls instead of reaching into a closure.
import functools
class CountCalls:
def __init__(self, func):
functools.update_wrapper(self, func)
self.func = func
self.calls = 0
self.failures = 0
def __call__(self, *args, **kwargs):
self.calls += 1
try:
return self.func(*args, **kwargs)
except Exception:
self.failures += 1
raise
def reset(self):
self.calls = self.failures = 0
class RateLimited:
def __init__(self, limit):
self.limit = limit
self.tokens = limit
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
if self.tokens <= 0:
raise RuntimeError("rate limit exceeded")
self.tokens -= 1
return func(*args, **kwargs)
wrapper.parent = self
return wrapper
@CountCalls
def validate(payload):
if not payload:
raise ValueError("empty")
return payload
print(validate("x"), validate.calls) # x 1
try:
validate("")
except ValueError:
pass
print(validate.calls, validate.failures) # 2 1
validate.reset()
print(validate.calls) # 0
@RateLimited(2)
def step():
return "ok"
print(step(), step()) # ok ok
try:
step()
except RuntimeError as exc:
print("blocked:", exc)
Note that CountCalls is used without parentheses â it receives the function directly â while RateLimited takes configuration first and returns the decorator. That is the difference between a decorator and a decorator factory, and choosing the wrong one produces the classic TypeError: 'NoneType' object is not callable.
Decorating methods and classes
Ordering becomes critical on methods. Decorators apply bottom up, so the one written closest to the function runs first and the one written highest runs last. With @classmethod above your decorator, your wrapper receives the plain function and the class binding happens outside it, so cls arrives as the first argument and attribute lookups on the bound method still reach your wrapper. Reverse the two and your decorator receives a classmethod object instead of a function, which fails later with an obscure TypeError about an object not being callable. The staticmethod case is the mirror image: keep your decorator closest to the function and staticmethod above it, and the name resolves to your wrapper unchanged.
Class decorators operate on the class object and return a replacement, which is the natural place for registration, interface enforcement, and annotation injection. Unlike a metaclass, a class decorator affects only the decorated class, which keeps the blast radius small. For behaviour that must apply to every subclass, __init_subclass__ remains the better tool.
import functools
def count_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
wrapper.calls += 1
return func(*args, **kwargs)
wrapper.calls = 0
return wrapper
class Service:
@classmethod
@count_calls
def create(cls, name):
return cls.__name__ + ":" + name
@count_calls
@staticmethod
def ping():
return "pong"
print(Service.create("a"), Service.create.calls) # Service:a 1
print(Service.ping(), Service.ping.calls) # pong 1
def register(cls):
cls.registered = True
return cls
@register
class Handler:
def handle(self, payload):
return payload
print(Handler.registered, Handler().handle(5)) # True 5
The counter stays reachable through Service.create.calls because the bound method delegates attribute reads to the wrapped function underneath. If that surprises you, it is a useful reminder that decorators compose left to right in the source but inside out at execution â write a three-line experiment before debugging a production stack.
Choosing the right decorator shape
Five shapes cover essentially all decorator problems, and the choice follows from what the decorator needs to know and when.
| Shape | Receives | Use when |
|---|---|---|
| Plain function | The function | Stateless wrapping is enough |
Function factory via () | Configuration, then the function | Behaviour varies per use site |
Class with __call__ | The function in __init__ | Per-decoration state you want to inspect |
| Class factory | Configuration, returns the decorator | Both configuration and accumulated state |
| Registration decorator | The function or class | Building a plugin or dispatch table |
A decorator is also the wrong tool when the behaviour must be toggled at run time rather than at import. Wrapping the function decides the behaviour once, when the module loads; if a flag must change per request, pass it as an argument or read it inside the wrapper so the decision happens at call time.
import functools
import time
def memoize(maxsize=128):
def decorator(func):
cache = {}
hits = {"n": 0}
@functools.wraps(func)
def wrapper(*args):
if args in cache:
hits["n"] += 1
return cache[args]
result = func(*args)
if len(cache) >= maxsize:
cache.clear()
cache[args] = result
return result
wrapper.cache = cache
wrapper.stats = hits
return wrapper
return decorator
@memoize(maxsize=64)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(60), fib.stats["n"]) # 1548008755920 with warm cache hits
The wrapper.cache and wrapper.stats attributes are the inspection payoff of the class-or-closure choice: a test can clear the cache directly, and a health endpoint can report hit rates without any introspection tricks.
Debugging decorated code
Decorators hide frames, and that is exactly what makes them annoying to debug. The standard remedies are inspect.unwrap, which peels layers until __wrapped__ runs out; functools.partial-style delegation that forwards __name__ for logging; and, in tests, asserting on the unwrapped function when the assertion is about behaviour rather than about the wrapper's side effects. Most tracebacks still show the wrapper frame, so naming wrappers clearly â or using functools.wraps so the frame reads like the original â pays for itself the first time something breaks at 2 a.m.
A few rules keep decorated code debuggable. Never swallow exceptions without re-raising or translating with raise ... from. Keep wrappers transparent: if the wrapper changes argument handling, the decorator is no longer a drop-in and the signature must be documented. And avoid stacking more than three decorators without a comment explaining the order, because every additional layer multiplies the reading cost for whoever maintains this next.
Common Mistakes
Forgetting functools.wraps in a wrapper
Fix: Apply @functools.wraps(func) so name, docstring, signature, and __wrapped__ survive for introspection
Assuming a stack of decorators applies top to bottom
Fix: Decorators apply bottom up â the lowest one wraps the function first, and each layer above wraps the result
Confusing a decorator with a decorator factory
Fix: Add a parameterised layer only when called with parentheses; otherwise the function itself is the decorator
Changing call semantics inside a wrapper without documenting it
Fix: Forward *args and **kwargs unchanged, or state the new signature explicitly in the docstring
Swallowing exceptions inside a wrapper to be safe
Fix: Re-raise or translate with raise ... from so failures are never silently converted into None
Best Practices
- Always use functools.wraps or functools.update_wrapper on returned wrappers
- Write a one-line comment above decorator stacks that depend on ordering
- Expose mutable decorator state as attributes so tests can reset and assert on it
- Prefer a class when a decorator needs several methods or shared state
- Keep run-time toggles inside the wrapper rather than deciding at decoration time
Interview Questions
Q1: In what order do stacked decorators apply?
Bottom up. The function is passed to the lowest decorator first, and each decorator above receives the result of the one below. Execution order is the reverse: the topmost wrapper runs before everything it wraps.
Q2: How does a decorator factory differ from a plain decorator?
A plain decorator receives the function directly. A factory is called with configuration and returns the decorator that actually receives the function, which is why @repeat(3) adds an extra layer of nesting.
Q3: Why does an undecorated wrapper break inspect.signature?
The wrapper defines its own parameters, typically *args and **kwargs, and without functools.wraps the link to the original is lost. wraps copies the metadata and sets __wrapped__, allowing inspect to recover the real signature.
Key Takeaways
- Decoration is rebinding: the decorator's return value becomes the callable
- Stacks apply bottom up and execute outside in â know which layer your metrics measure
- functools.wraps preserves name, doc, signature, and the __wrapped__ link
- Class decorators buy inspectable state; factories buy per-site configuration
- Decorator order around classmethod and staticmethod changes what your wrapper receives