A decorator is a function that takes another function and returns an improved version of it. The @ symbol is shorthand for that step. You will meet decorators constantly in Django (@login_required) and Flask (@app.route), so understanding them makes those frameworks easier to read.
Functions are values
In Python, functions can be passed around like numbers. That is the key idea: a decorator receives a function and returns a new one.
A simple timing decorator
import time
def timed(func):
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter() - start:.4f}s")
return result
return wrapper
@timed
def build_report():
return sum(range(1_000_000))
@timed above the function is the same as writing build_report = timed(build_report).
Why *args and **kwargs
The wrapper accepts any arguments and passes them on, so the decorator works with any function.
Keep the name with functools.wraps
Add @functools.wraps(func) above wrapper. Without it, the function’s name and documentation are replaced by the wrapper’s, which confuses debugging and help output.
Decorators with arguments
To pass options, such as a number of retries, add one more layer: a function that returns the decorator. This pattern is common in retry and caching libraries.
Where you will see them
- Django:
@login_required,@require_POST,@cache_page. - Flask:
@app.get("/courses"). - Standard library:
@functools.lru_cachefor caching results.
Related: Python functions for beginners and Django authentication.
These topics are practised with projects in our Python Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
