Decorators
In short
A decorator is a function that takes another function and returns an improved version of it. Writing @timer above def work(): is short for work = timer(work). Decorators add behaviour such as logging, timing, retries or caching without touching the function's own code.
Step 1: functions inside functions
def make_multiplier(factor: int):
def multiply(x: int) -> int:
return x * factor # remembers factor
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(10), triple(10))Output
20 30
The inner function remembers factor even after make_multiplier has finished. That's called a closure, and it's the engine behind every decorator.
Step 2: a function that wraps a function
def shout(func):
def wrapper(*args, **kwargs):
result = func(*args, **kwargs)
return result.upper()
return wrapper
def greet(name: str) -> str:
return f"hello, {name}"
loud_greet = shout(greet)
print(loud_greet("ana"))Output
HELLO, ANA
Step 3: the @ syntax
import functools
def shout(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs).upper()
return wrapper
@shout
def greet(name: str) -> str:
"""Greet someone."""
return f"hello, {name}"
print(greet("ben"))
print(greet.__name__, "-", greet.__doc__)Output
HELLO, BEN greet - Greet someone.
A practical decorator: timing
import functools
import time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.3f}s")
return result
return wrapper
@timer
def total(n: int) -> int:
return sum(range(n))
result = total(2_000_000)
print(result)Decorators with arguments
import functools
def retry(times: int):
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 err:
print(f"Attempt {attempt} failed: {err}")
raise ConnectionError(f"gave up after {times} attempts")
return wrapper
return decorator
calls = 0
@retry(times=3)
def fetch() -> str:
global calls
calls += 1
if calls < 3:
raise ConnectionError("server busy")
return "data received"
print(fetch())Output
Attempt 1 failed: server busy Attempt 2 failed: server busy data received
A decorator with arguments needs one extra layer: retry(times=3) returns the actual decorator, which then wraps the function.
Built-in decorators you'll use
from functools import cache
@cache
def fib(n: int) -> int:
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80))
print(fib.cache_info().hits > 0)Output
23416728348467685 True
@functools.cacheand@lru_cacheremember results of expensive calls.@property,@staticmethodand@classmethodshape methods in classes.@dataclasswrites class boilerplate.- Web frameworks use decorators for routes, e.g.
@app.get("/items")in FastAPI.
Practice
Write a decorator log_call that prints Calling NAME before running the function (use func.__name__) and then returns the function's result. Decorate def add(a, b): return a + b with it and print add(2, 3).
Expected output:
Calling add 5