Module 17 · Advanced Python Concepts — topic 9 of 14
Decorators
Wrapping functions to add behaviour: the @ syntax, writing decorators with *args and **kwargs, preserving metadata with functools.wraps, decorators that take arguments, and stacking decorators.
Learning objectives
- Write decorators with functools.wraps
- Create decorators that take arguments
- Recognise common uses such as logging, retrying and validation
Definition
A decorator is a callable that takes a function and returns a replacement, usually a wrapper that adds behaviour before or after calling the original. @decorator above a def is shorthand for func = decorator(func).
Introduction
Logging every call, timing functions, checking permissions, retrying network calls — decorators add such behaviour without touching the function's own code.
Why it matters
Decorators keep cross-cutting concerns in one place and appear throughout frameworks (@app.route, @property, @pytest.fixture).
Detailed explanation
@my_decorator on a function means func = my_decorator(func), applied once when the function is defined.
A typical decorator defines an inner wrapper(*args, **kwargs) that does extra work, calls func(*args, **kwargs), and returns its result.
Without functools.wraps, the wrapper hides the original's __name__ and __doc__; @functools.wraps(func) copies them over.
A decorator with arguments is a function that returns a decorator: @retry(times=3) calls retry(3), and the result decorates the function.
Stacked decorators apply from the bottom up: @a above @b means func = a(b(func)).
Decorators can store state on the wrapper (such as call counts) or validate arguments before calling the original.
Built-in decorators include @property, @staticmethod, @classmethod, @functools.lru_cache and @dataclasses.dataclass.
Because decoration happens when the def statement runs, any code in the decorator outside the wrapper runs once at import time, while code inside the wrapper runs on every call. Keeping that distinction in mind explains most decorator surprises.
Syntax
- @d means func = d(func).
- Always use functools.wraps.
- Factories create decorators with arguments.
Code examples
A logging decorator
calling add(2, 3) add returned 5
Why functools.wraps matters
wrapper None g Docs for g.
More examples
Retrying and validating
attempt 1 failed: timeout attempt 2 failed: reset data 4.0 sqrt needs a positive number, got -4
Step-by-step explanation
- retry(times=3) returns the real decorator, which wraps fetch.
- The first two simulated calls raise ConnectionError and are retried; the third succeeds.
- require_positive checks the argument before the original function runs.
Expected output
Running “Retrying and validating” prints exactly:
Practical applications
- Flask's @app.route and FastAPI's @app.get.
- Authentication checks such as @login_required.
Best practices
- Use functools.wraps in every wrapper.
- Accept *args and **kwargs.
- Keep decorators small and focused.
Common mistakes
Forgetting to return the result
Avoid
Prefer
Without return, every decorated function returns None.
Calling the function in the decorator
Avoid
Prefer
Decorators run at definition time; the call should happen inside the wrapper.
Important notes
- Classes can also be decorated, and classes with __call__ can act as decorators.
Key takeaways
- Decorators wrap functions to add behaviour.
- functools.wraps keeps the original's metadata.
- Decorator factories take arguments.
Try it yourself
- 1Write a @count_calls decorator that records how many times a function was called.
- 2Write @timed that prints how long a function took.
Finished reading? Mark it complete to update your dashboard.
Suggested practice
2 questions test this exact topic. Answers and explanations are revealed after you submit.
- AdvancedWhat is printed?
- AdvancedWhat is printed?