Python Tutorial 0/52 lessons ~6 min read Lesson 35
Decorators
A decorator is a function that takes a function and returns a new function.
Course progress0%
Focus
8 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
Introduction
A decorator is a function that takes a function and returns a new function. Used for logging, timing, caching, auth, retries, route registration.
Understanding the topic
Core concepts to understand:
@deco=fn = deco(fn)- Use
functools.wrapsto preserve metadata. - Decorators with args = factory returning a decorator.
- Class-based decorators with
__call__.
Syntax reference
Visual flow / code:
python
from functools import wrapsimport timedef timed(fn):@wraps(fn)def wrapper(*args, **kwargs):start = time.perf_counter()result = fn(*args, **kwargs)print(f"{fn.__name__}: {time.perf_counter()-start:.3f}s")return resultreturn wrapper@timeddef slow():time.sleep(0.5)# Parameterized decoratordef retry(n: int):def deco(fn):@wraps(fn)def wrapper(*a, **kw):for i in range(n):try: return fn(*a, **kw)except Exception: passraisereturn wrapperreturn deco
Execution workflow
1Decorators Workflow
1 / 4@deco = fn = deco(fn)
@deco = fn = deco(fn)
Real-world use
FastAPI, Flask, Django, Celery, pytest — all use decorators as their public API. They're a Python superpower.
Best practices
- Always
@wraps. - Keep decorator logic small.
- Parameterized decorators = 3 nested fns.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat's a decorator?+
Answer
A decorator is a callable that takes a function (or class) and returns a replacement, usually a wrapper that adds behavior. The syntax
@deco above def f is shorthand for f = deco(f). Common uses include logging, caching, authorization checks, and registration.Follow-up
Can you apply more than one decorator? In what order do they run?
2IntermediateQuestionWhy @wraps?+
Answer
A wrapper function replaces the original, so without help the decorated function reports the wrapper's
__name__ and __doc__. functools.wraps copies the original's name, docstring, module, and other metadata, and sets __wrapped__. This keeps debugging, documentation tools, and introspection (including inspect.signature) working properly.Follow-up
What attributes does
wraps copy by default?3IntermediateQuestionWalk through a parameterized decorator.+
Answer
A parameterized decorator is a three-level structure: an outer function takes the arguments such as
retries=3 and returns a real decorator; that decorator takes the function and returns a wrapper; the wrapper calls the function with *args, **kwargs. So @retry(3) first evaluates retry(3), then applies the result to the function. Use @wraps on the wrapper.Follow-up
How would you let the decorator work both with and without parentheses?
Summary
In summary: Functions transforming functions. Wraps preserves identity.
Ready to mark this lesson complete?Track your journey across the entire course.