Decorators & Metaprogramming

Difficulty: Advanced

Question

Explain Python decorators. How do they work under the hood, and can you write a custom decorator, including one that takes arguments?

Answer

A decorator is a callable that takes a function (or class) and returns a replacement, usually a wrapper that adds behaviour before or after the original runs. The @timer line above def fetch() is pure syntax sugar for fetch = timer(fetch), executed once when the def statement runs. Decorators work because Python functions are first-class objects and inner functions form closures over the function they wrap.

What actually happens when Python sees @decorator

  1. Python executes the def and creates a function object.
  2. It calls the decorator with that function object as the only argument.
  3. Whatever the decorator returns is bound to the original name.

So decoration happens at import time, not call time. A decorator that prints something will print as soon as the module is imported. The wrapper it returns is what runs on every call, and it reaches the original function through a closure: the inner function keeps a reference to func in its enclosing scope even after the decorator has returned.

When you stack decorators, they apply bottom-up: @a over @b over def f means f = a(b(f)). At call time, a's wrapper runs first and calls into b's wrapper.

Decorators with arguments are one level deeper

@retry(times=3) is not a decorator itself. retry(times=3) is called first and must return a decorator, which is then applied to the function. That gives three nested levels:

Forgetting the middle layer is the most common bug when writing these in an interview. Since Python 3.9 (PEP 614), any expression is allowed after @, so things like @handlers["login"] are legal.

Why functools.wraps matters

Without @functools.wraps(func), the wrapper replaces the original's __name__, __doc__, __qualname__, __module__ and annotations. Logs show wrapper instead of charge_card, help() loses the docstring, and frameworks that inspect signatures (FastAPI, Click, pytest fixtures) can break. wraps copies that metadata and also sets __wrapped__, so inspect.signature() and inspect.unwrap() can see the real function underneath.

Where decorators show up in real code

Use caseExample
Caching@functools.cache, @functools.lru_cache(maxsize=256)
Web routing@app.get("/orders/{id}") in FastAPI, @app.route in Flask
Auth and permissions@login_required in Django
Retries and timeoutstenacity.retry around a flaky payment gateway call
Class tooling@dataclass, @property, @staticmethod, @classmethod

Class decorators work the same way: @dataclass receives the class object, adds __init__, __repr__ and __eq__, and returns it. A class can also act as a decorator if it implements __call__, which is handy when the decorator needs state such as a call counter.

Common mistakes and gotchas

How @decorator rewires a function. Decoration runs once at definition time; the returned wrapper runs on every call.
  1. def charge() runs: Python builds the original function object.
  2. timer(charge) is called: The decorator receives the function as an argument.
  3. wrapper is returned: A closure that still references the original.
  4. Name charge now points to wrapper: charge = timer(charge) has rebound the name.
  5. charge() call runs wrapper: Wrapper adds behaviour, then calls the original.

Code examples

A timing decorator with functools.wraps

import functools
import time

def timer(func):
    @functools.wraps(func)          # keep name, docstring, __wrapped__
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return func(*args, **kwargs)
        finally:
            elapsed = time.perf_counter() - start
            print(f"{func.__name__} took {elapsed:.3f}s")
    return wrapper

@timer
def settle_payments(n):
    """Pretend to settle n UPI transactions."""
    time.sleep(0.2)
    return n

print(settle_payments(50))
print(settle_payments.__name__, settle_payments.__doc__)

The try/finally makes sure timing is logged even if the function raises. Without @wraps the last line would print 'wrapper None'.

Decorator factory: retry with arguments

import functools
import time

def retry(times=3, delay=0.5, exceptions=(ConnectionError,)):
    def decorator(func):                    # level 2: gets the function
        @functools.wraps(func)
        def wrapper(*args, **kwargs):       # level 3: runs per call
            for attempt in range(1, times + 1):
                try:
                    return func(*args, **kwargs)
                except exceptions as exc:
                    if attempt == times:
                        raise
                    print(f"attempt {attempt} failed: {exc}")
                    time.sleep(delay * attempt)   # simple linear backoff
        return wrapper
    return decorator                        # level 1 returns the decorator

@retry(times=3, delay=0.1)
def call_gateway():
    raise ConnectionError("gateway timeout")

try:
    call_gateway()
except ConnectionError as e:
    print("gave up:", e)

retry(times=3, delay=0.1) runs first and returns decorator, which is then applied to call_gateway. Only listed exceptions are retried, so bugs like TypeError fail fast.

Stateful class-based decorator

import functools

class CountCalls:
    def __init__(self, func):
        functools.update_wrapper(self, func)
        self.func = func
        self.calls = 0

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

@CountCalls
def greet(name):
    return f"Hi {name}"

greet("Asha"); greet("Ravi")
print(greet.calls)

Any callable can be a decorator. A class keeps state as attributes, and update_wrapper does the same job as @wraps.

Key points

Common follow-up questions

Interview tips

Concepts covered

Decorators, Closures, functools.wraps, Decorator Factory, Class Decorators

More Python Interview questions