The @ symbol you see above functions in Django, Flask, FastAPI and pytest is a decorator — a function that wraps another function to add behaviour. To understand decorators you first need two ideas: functions are first-class values, and closures remember their surroundings. This chapter builds up to writing your own.
Functions are values
In Python a function is an ordinary object. You can assign it to a variable, pass it as an argument, and return it from another function — exactly like a number or string:
def shout(text):return text.upper()f = shout # assign — no parenthesesprint(f("hi")) # HIdef apply(fn, value):return fn(value) # pass a function inprint(apply(shout, "hello")) # HELLO
Closures
A closure is a function that remembers variables from the scope where it was created, even after that scope has finished. An outer function can build and return a customised inner function:
def multiplier(factor):def multiply(n):return n * factor # 'factor' is rememberedreturn multiplydouble = multiplier(2)triple = multiplier(3)print(double(10)) # 20print(triple(10)) # 30
Decorators
A decorator is just a function that takes a function and returns a new function wrapping it. The @name syntax above a definition is shorthand for "reassign this function to name(this_function)":
def logged(fn):def wrapper(*args, **kwargs):print(f"calling {fn.__name__}")result = fn(*args, **kwargs)print(f"{fn.__name__} returned {result}")return resultreturn wrapper@logged # same as: greet = logged(greet)def greet(name):return f"Hi {name}"greet("Aanya")# calling greet# greet returned Hi Aanya
The *args, **kwargs in the wrapper let it wrap any function regardless of its signature. Common real uses: logging, timing, caching, access control, retries.
Preserving metadata
Wrapping replaces the original function, so greet.__name__ becomes "wrapper" — which breaks debugging and docs. functools.wraps copies the original's identity onto the wrapper:
from functools import wrapsdef logged(fn):@wraps(fn) # keep fn's name, docstring, etc.def wrapper(*args, **kwargs):return fn(*args, **kwargs)return wrapper
Decorators with arguments
To pass options to a decorator (like @retry(times=3)), add one more layer — a function that returns a decorator:
from functools import wrapsdef repeat(times):def decorator(fn):@wraps(fn)def wrapper(*args, **kwargs):for _ in range(times):result = fn(*args, **kwargs)return resultreturn wrapperreturn decorator@repeat(times=3)def ping():print("ping")ping() # prints ping three times
Practice
Write a timer decorator that prints how long the wrapped function took (use time.perf_counter() and @wraps). Then write a repeat(n) decorator-with-arguments and apply both to a function.
Key takeaways
- 01Functions are first-class values: assign, pass and return them like any object.
- 02A closure is an inner function that remembers variables from where it was created.
- 03A decorator takes a function and returns a wrapped one; @name is shorthand for name(fn).
- 04Use *args/**kwargs in the wrapper to decorate any signature, and @wraps to keep the original identity.
- 05For decorator arguments (@retry(3)), add an extra layer: a function that returns the decorator.
