Difficulty: Advanced
Explain Python decorators. How do they work under the hood, and can you write a custom decorator, including one that takes arguments?
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.
def and creates a function object.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.
@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 configurationdecorator(func): receives the functionwrapper(args, *kwargs): runs on every callForgetting 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.
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.
| 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.
return wrapper() runs it at decoration time.return func(args, *kwargs), otherwise every decorated function returns None.def wrapper(x)) instead of forwarding args, *kwargs.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.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'.
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.
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.
Decorators, Closures, functools.wraps, Decorator Factory, Class Decorators