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).
Example
1from functools import wrapsβ2import timeβ3β4def 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 rβ11 return wrapperβ12β13@timedβ14def work():β15 return sum(range(100_000))β16β17work()βTry it live Β· Python runs in your browser
Loading playgroundβ¦
Checkpoint quiz
Question 1 / 2
@decorator above def f is equivalent to: