A decorator wraps a function to add behaviour without changing its code — logging, timing, caching, access checks.
Functions are objects
In Python you can pass functions as arguments and return them from other functions. Decorators build on this.
How it works
@timer
def report(): ...
is the same as report = timer(report).
The decorator returns a wrapper function that runs extra code before and/or after calling the original.
Use functools.wraps
@functools.wraps(func) on the wrapper keeps the original function's name and docstring.
Accept any arguments
Write the wrapper as def wrapper(*args, **kwargs): so it works with any function.
Decorators with arguments
@retry(times=3) needs one more level: a function that returns a decorator.
Built-in and common decorators
@property,@classmethod,@staticmethod@functools.cache/@lru_cache— remember results@dataclass- Framework routes:
@app.route("/")in Flask,@app.get("/")in FastAPI
Example
import functools, time, random
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
return result
return wrapper
def retry(times=3):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, times + 1):
try:
return func(*args, **kwargs)
except ConnectionError as e:
print(f"Attempt {attempt} failed: {e}")
raise ConnectionError("All attempts failed")
return wrapper
return decorator
@timer
def slow_sum(n):
return sum(range(n))
@retry(times=3)
def flaky_api():
if random.random() < 0.6:
raise ConnectionError("timeout")
return "data received"
print(slow_sum(5_000_000))
print(flaky_api())
@functools.cache
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80))
Prints the sum and how long it took (e.g. "slow_sum took 0.080s"), up to two failed attempts before "data received" (random, and it may fail all three times), and fib(80) = 23416728348467685 instantly thanks to caching.