# Decorators & Metaprogramming

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

Canonical: https://www.internhack.in/learn/interview/python-interview/python-decorators
Last updated: 2026-11-28

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:

- `retry(times, delay)`: the factory, captures configuration
- `decorator(func)`: receives the function
- `wrapper(args, *kwargs)`: runs on every call

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 case | Example |
| --- | --- |
| 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 timeouts | `tenacity.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

- Calling the function instead of returning the wrapper: `return wrapper()` runs it at decoration time.
- Dropping the return value: the wrapper must `return func(args, *kwargs)`, otherwise every decorated function returns `None`.
- Hard-coding the signature (`def wrapper(x)`) instead of forwarding `args, *kwargs`.
- Decorating `async def` functions with a sync wrapper: the wrapper returns an un-awaited coroutine, so timing and try/except logic measure nothing. Write an `async def wrapper` that awaits `func`.
- Mutable state in the closure is shared across all calls and threads, so a counter needs a lock under threading.

**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

- @dec above def f is exactly f = dec(f), run once at definition (import) time
- Stacked decorators apply bottom-up and execute top-down at call time
- Decorators with arguments need three levels: factory, decorator, wrapper
- Always use functools.wraps; it also sets \__wrapped_\_ for introspection
- Async functions need an async wrapper that awaits the original

## Common follow-up questions

- What breaks if you leave out functools.wraps?
- How would you write a decorator that works with and without parentheses, like @retry and @retry(times=5)?
- How do @property and @classmethod work as decorators?
- How would you decorate an async function correctly?
- In what order do stacked decorators run?

## Interview tips

- Start by saying @dec is f = dec(f); it shows you understand there is no magic
- Write the retry or timer decorator from memory with \*args, \*\*kwargs and @wraps; interviewers watch for both
- Mention a real use like FastAPI routes, Django login_required or lru_cache to show production familiarity

## Concepts covered

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

Next: [Generators & Iterators](https://www.internhack.in/learn/interview/python-interview/python-generators) · [All of Python Interview](https://www.internhack.in/learn/interview/python-interview)

## More Python Interview questions

- [GIL & Concurrency](https://www.internhack.in/learn/interview/python-interview/python-gil)
- [Variables & Data Types](https://www.internhack.in/learn/interview/python-interview/python-variables-types)
- [Strings & String Methods](https://www.internhack.in/learn/interview/python-interview/python-strings)
- [Lists, Tuples & Sets](https://www.internhack.in/learn/interview/python-interview/python-lists-tuples-sets)
- [Dictionaries & Operations](https://www.internhack.in/learn/interview/python-interview/python-dictionaries)
- [Control Flow & Loops](https://www.internhack.in/learn/interview/python-interview/python-control-flow)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Python Interview](https://www.internhack.in/learn/interview/python-interview)
