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: