L5·Intermediate/Advanced
🎀Decorators
Functions that wrap functions.
decorator@wraps
§ 1Just syntax sugar
@dec above def f is f = dec(f). Decorators are functions taking a callable and returning a callable.
§ 2functools.wraps
Preserves __name__ and __doc__ on the wrapper — always use it.
§ 3Parameterized
A 'decorator factory' returns the actual decorator: @retry(3) → retry(3)(f).
Worked example
1from functools import wraps2import time34def timed(fn):5 @wraps(fn)6 def wrapper(*a, **k):7 t = time.perf_counter()8 r = fn(*a, **k)9 print(f"{fn.__name__}: {time.perf_counter()-t:.4f}s")10 return r11 return wrapper1213@timed14def work():15 return sum(range(100_000))1617work()Try it live · Python runs in your browser
Loading playground…
Checkpoint quiz
Question 1 / 2
@decorator above def f is equivalent to:
Lesson test
Take an 8-question test on “Decorators” — concepts, output prediction, bug spotting and interview questions.