🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Decorator Patterns: Parameters, Stacking, and State

Python DecoratorsDecoratorsđŸŸĸ Free Lesson

Decorator Patterns: Parameters, Stacking, and State

Decorators are the language feature most often used before it is understood. The syntax is trivial — @name above a function means "replace it with name(func)" — but the consequences ripple: identity, signature, metadata, mutability, and the order in which multiple wrappers run all change the moment a decorator is applied. That misunderstanding produces the two failures you meet in real codebases: wrappers that break help() and introspection because they forgot functools.wraps, and parameterised decorators that accidentally share one piece of state across every function in the process.

This lesson builds the mental model in pieces: what the decorator call actually returns, how to add parameters without writing four nested functions you cannot read, how stacking orders behaviour, and when a class is a clearer decorator than a closure.


What the syntax desugars to

Writing @timer above def report() is exactly equivalent to defining report and then rebinding the name: report = timer(report). The old function object is gone from the namespace unless the decorator keeps a reference to it, which is why a wrapper that returns a new function makes the original name point at something else entirely. Every decorator is therefore a function of one argument that returns a replacement — nothing more, and nothing less.

python
import time
from functools import wraps

def timed(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        started = time.perf_counter()
        result = func(*args, **kwargs)
        elapsed = time.perf_counter() - started
        print(f"{func.__name__} took {elapsed * 1000:.1f} ms")
        return result
    return wrapper

@timed
def monthly_report(rows):
    return sorted(rows, key=lambda r: r["total"], reverse=True)

print(monthly_report.__name__)   # monthly_report — not 'wrapper'

functools.wraps copies __name__, __doc__, __module__, __qualname__, and the __wrapped__ attribute that lets inspect.signature see through the wrapper. Omit it and every log line, profiler, and automatic API doc in your application starts naming the inner function wrapper — a small omission with outsized debugging cost.

Parameters without the extra nesting

A decorator that takes arguments needs one more function, because @rate_limit(5) runs before it ever sees the decorated function. Beginners often flatten this by writing def decorator(...) and expecting it to receive the function, which silently makes the decorator return None and replaces your function with None. The reliable shape is always: outer function takes the decorator's arguments, middle function takes the target, inner function takes the target's arguments.

python
def rate_limit(calls_per_second=1.0):
    min_interval = 1.0 / calls_per_second
    last_called = {"t": 0.0}

    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            elapsed = time.monotonic() - last_called["t"]
            if elapsed < min_interval:
                time.sleep(min_interval - elapsed)
            last_called["t"] = time.monotonic()
            return func(*args, **kwargs)
        return wrapper
    return decorator

@rate_limit(calls_per_second=4)
def push_metric(name, value):
    print(f"push {name}={value}")

Note the mutable dict holding the timestamp: a closure can rebind a name only inside its own scope, so shared mutable state is how wrappers remember things between calls. Keep that state inside the decorator application (one dict per decorated function), never at module level, or every decorated function will throttle against the same clock.

Stacking order runs bottom-up

When several decorators sit above one function, the source order is the reverse of the execution order: the decorator closest to the def wraps first, and each subsequent decorator wraps the result. Swapping two lines changes which one sees the other's timing or output, and the difference is observable.

python
def bold(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return f"<b>{func(*args, **kwargs)}</b>"
    return wrapper

def italic(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return f"<i>{func(*args, **kwargs)}</i>"
    return wrapper

def badge(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return f"[{func(*args, **kwargs)}]"
    return wrapper

@bold
@italic
@badge
def greet(name):
    return f"Hello, {name}"

print(greet("Ada"))   # <b><i>[Hello, Ada]</i></b>

The outermost decorator in the source is the outermost wrapper at runtime, so logging decorators placed first in a stack see the final return value, while auth checks placed first run before anything else does. Choose placement deliberately: an authentication decorator applied below a caching decorator would let cached responses bypass the permission check.

When a class is clearer than a closure

A class decorator is the same contract — constructed with the function, called with the arguments — but it makes state explicit as attributes instead of hiding it in a closure, and it can expose extra methods such as a reset hook for tests.

python
class CountCalls:
    """Decorator instance: counts invocations across the process."""
    def __init__(self, func):
        self.func = func
        self.calls = 0
        wraps(func)(self)

    def __call__(self, *args, **kwargs):
        self.calls += 1
        return self.func(*args, **kwargs)

    def reset(self):
        self.calls = 0

@CountCalls
def send_digest(recipients):
    return f"sent to {len(recipients)} people"

send_digest(["[email protected]", "[email protected]"])
send_digest(["[email protected]"])
print(send_digest.calls)          # 2 — state lives on the object

Because the decorated name now refers to the CountCalls instance, that instance is where the counter lives — a property available to tests and metrics code. The trade-off is that the result is no longer a plain function, so isinstance(send_digest, types.FunctionType) is false; for most applications that is irrelevant, but it is worth knowing before you build a registry that assumes functions.

Choosing the right wrapper shape

Different jobs want different decorator structures, and picking the wrong one is what makes decorators feel harder than they are.

GoalPreferred shapeKey detail
Cross-cutting concern (timing, logging)Plain function decorator with wrapsMust forward *args, **kwargs untouched
Tunable behaviour (limits, retries)Parameterised decorator, three-level nestingRemember the extra return decorator
Accumulated state (call counts, cache)Class decorator or closure over a mutable cellKeep state per application
Registering handlers by nameDecorator that returns the original functionStore in a dict, do not wrap
Transforming arguments or resultsWrapper with explicit signatureUse functools.wraps so signatures introspect
Simple memoisationfunctools.lru_cacheDo not hand-roll it
python
ROUTES = {}

def route(path, methods=("GET",)):
    def decorator(func):
        ROUTES[(path, frozenset(methods))] = func
        return func          # identity — no wrapper at all
    return decorator

@route("/health", methods=("GET",))
def health(request):
    return {"status": "ok"}

assert ROUTES[("/health", frozenset({"GET"}))] is health

This last pattern is the one most people forget: a decorator does not have to wrap anything. Registration decorators simply record the function and hand it back unchanged, which keeps routing metadata attached without adding a call frame to every request.

Debugging decorated code

Once you have a stack of wrappers, inspect.signature (which follows __wrapped__), python -m pdb, and timeit all behave correctly only if every layer preserved metadata. If a decorator ever needs to expose the original, keep the reference yourself — an attribute such as wrapper.__wrapped__ is the convention, and both functools.wraps and inspect already honour it. Finally, remember that a decorator applied to a method receives the bound method as func, so instance and class state arrive in self through *args exactly as they would without the decorator — there is nothing special about methods here, which is usually a relief the first time you add one to a class.

A second debugging trap is exceptions raised inside the wrapper itself. If your timing code divides by zero or your throttle reads a lock that was never initialised, the failure appears to come from the decorated function even though the user's code was innocent. Keep the wrapper's own logic minimal, and if it can fail, let that failure be as explicit as anything else the decorator promises. The same applies to return values: a wrapper that accidentally returns None because it forgot to propagate result will look like a bug in the business logic for hours before anyone suspects the six-line function above it.

Common Mistakes

Forgetting functools.wraps so logs and help() show 'wrapper'

Fix: Decorate the inner function with @wraps(func) every single time

Parameterised decorator written with only two levels of nesting

Fix: Outer takes the arguments, middle takes the function, inner takes the call — always three levels

Storing timing or throttle state at module level so all functions share it

Fix: Keep mutable state inside the decorator application so each target gets its own

Placing an auth decorator below a caching decorator

Fix: Stack so security checks wrap everything else — source order is outermost first

Hand-rolling a cache instead of using functools.lru_cache

Fix: Use the standard tool unless you need custom eviction or statistics

Best Practices

  • Always forward *args and **kwargs unchanged unless transforming them is the point
  • Write one decorator per concern so they can be stacked and reordered safely
  • Prefer a class when state accumulates; attributes are clearer than closure cells
  • Test decorators in isolation — they are ordinary functions with an ordinary contract
  • Use identity decorators for registration; wrapping is optional, not obligatory

Key Takeaways

  • @decorator is syntax for rebinding the name to decorator(func)
  • Parameterised decorators need three nested functions, with an explicit return of the middle one
  • Stacking applies bottom-up in execution while reading top-down in source
  • functools.wraps preserves identity, docs, and introspectable signatures
  • A decorator may simply register and return the function — no wrapper required
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement