Decorators
Decorator tasks are common in Python rounds: count the calls, log or time a function, retry a flaky call, cache a slow one. Each is about ten lines, but only if three ideas are clear. A function is a value. An inner function remembers the variables of the outer one. The wrapper replaces the original function.
Functions are values
Section titled “Functions are values”A function is an object like any other. You can put it in a dict, pass it as an argument and return it from another function. An event processor often picks the handler from a dict by the event type:
def on_purchase(event): return f"new subscription for {event['customer_id']}"
def on_refund(event): return f"refund for {event['customer_id']}"
handlers = {"purchase": on_purchase, "refund": on_refund}
event = {"type": "refund", "customer_id": "cus_02564"}print(handlers[event["type"]](event))refund for cus_02564sorted(rows, key=...) uses the same idea: you pass a function, and sorted calls it for every row.
Closures
Section titled “Closures”A function defined inside another function can read the outer function’s variables, even after the outer one has returned. This is a closure.
from decimal import Decimal, ROUND_HALF_UP
def make_fee(rate): def fee(amount): return (amount * rate).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) return fee
market_fee = make_fee(Decimal("0.15"))print(market_fee(Decimal("9.99")))1.50market_fee remembers rate. Reading an outer variable is free. Assigning to it is not: an assignment makes the name local to the inner function, and the local name has no value yet.
def count_calls(func): calls = 0
def wrapper(*args, **kwargs): calls += 1 return func(*args, **kwargs) return wrapper
@count_callsdef fee(amount): return amount * 2
fee(10)UnboundLocalError: cannot access local variable 'calls' where it is not associated with a valueThere are two ways out:
nonlocal callsin the wrapper. It works, but the counter lives inside the closure, and nobody outside can read it:fee.callsraisesAttributeError: 'function' object has no attribute 'calls'.- An attribute on the wrapper. After
@count_calls, the namefeeis the wrapper, sofee.callsis visible from outside. Set the attribute once, afterdef wrapper, and change it inside. The drill below asks for exactly this.
A decorator with functools.wraps
Section titled “A decorator with functools.wraps”import functools
def log_calls(func): @functools.wraps(func) # without this line: see the second output def wrapper(*args, **kwargs): result = func(*args, **kwargs) print(f"{func.__name__}{args} -> {result!r}") return result return wrapper
@log_callsdef normalise_channel(name): """Channel name in lower case, without spaces.""" return name.strip().lower()
normalise_channel(" North_Market ")print(normalise_channel.__name__, "|", normalise_channel.__doc__)print(normalise_channel.__wrapped__(" South_Market "))normalise_channel(' North_Market ',) -> 'north_market'normalise_channel | Channel name in lower case, without spaces.south_marketThe same code without the wraps line:
normalise_channel(' North_Market ',) -> 'north_market'wrapper | NoneAttributeError: 'function' object has no attribute '__wrapped__'Without wraps, logs, tracebacks and tools see every decorated function as wrapper, and the docstring is lost. With it, the name, the docstring and the signature that help() shows come from the original. __wrapped__ gives the original function, for example to test it without the decorator.
Two more details:
- The most common bug is a missing
returnin the wrapper. The decorated function then returnsNone. - Stacked decorators apply from the bottom up:
@aabove@babovedef fmeansf = a(b(f)).
What does functools.wraps do, and where do you put it?
Say your answer out loud first, then open it.
Show the answer
“It goes on the inner wrapper, because the wrapper replaces the original function. It copies the name, the docstring and the module of the original onto the wrapper, and it sets __wrapped__ to the original. So logs and tracebacks show the real name, help() and inspect.signature follow __wrapped__ to the real signature, and tests can call the original.”
A typical slip is to put @functools.wraps above the outer function. It belongs directly above def wrapper.
A decorator with a parameter
Section titled “A decorator with a parameter”@retry(times=3) first calls retry(times=3). That call returns the real decorator, and the decorator then receives the function. So there is one more level:
import functools
def retry(times, exceptions=(TimeoutError,)): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): for attempt in range(1, times + 1): try: return func(*args, **kwargs) except exceptions: print(f"attempt {attempt} failed") if attempt == times: raise return wrapper return decorator
answers = iter([TimeoutError("slow"), TimeoutError("slow"), "1.08"])
@retry(times=3)def fetch_rate(): answer = next(answers) if isinstance(answer, Exception): raise answer return answer
print(fetch_rate())print(fetch_rate.__name__)attempt 1 failedattempt 2 failed1.08fetch_rateA bare raise after the last attempt re-raises the last error with its original traceback. A real retry also waits between attempts and retries only temporary errors: see Errors and validation.
The usual mistake is @retry without parentheses. Then retry receives the function as times, and the first call fails:
TypeError: retry.<locals>.decorator() missing 1 required positional argument: 'func'Ready-made decorators
Section titled “Ready-made decorators”When the result never goes stale, you do not have to write a cache:
import functools
@functools.lru_cache(maxsize=128)def exchange_rate(currency): print(f"calling the rates API for {currency}") return {"EUR": "1.08", "GBP": "1.27"}[currency]
exchange_rate("EUR")exchange_rate("EUR")exchange_rate("GBP")print(exchange_rate.cache_info())calling the rates API for EURcalling the rates API for GBPCacheInfo(hits=1, misses=2, maxsize=128, currsize=2)functools.cache is the same without a size limit. Neither forgets an entry after some time. So neither fits data that changes, like an exchange rate that updates every hour. That is why a cache with expiry (TTL) is a separate task in Caching and rate limits. @property, @staticmethod, @classmethod and @dataclass are decorators too: see Classes and state.
Practice
Section titled “Practice”Write a decorator count_calls that counts how many times the function was called (in an attribute calls) and keeps the function's name.
Data and an example
The checks run after your code and can use these:
@count_callsdef charge(amount): return amount * 2
charge(1); charge(2)Example: charge.calls → 2
3 checks. Your own print() output is shown too.
import functools
def count_calls(func):
...
Show answer
Reference
import functools
def count_calls(func): @functools.wraps(func) def wrapper(*args, **kwargs): wrapper.calls += 1 return func(*args, **kwargs) wrapper.calls = 0 return wrapperChecks and the expected values
-
charge.calls→2 -
charge(5)→10 -
charge.__name__→'charge'
The wrapper replaces the function, so the counter lives on the wrapper: wrapper.calls = 0 after the definition, wrapper.calls += 1 inside. functools.wraps goes on the wrapper as well: it copies __name__ and __doc__ and adds __wrapped__. A decorator with a parameter, such as retry(times), is one level deeper.
Write retry(times, exceptions), a decorator with parameters: @retry(times=3, exceptions=(TimeoutError,)) calls the function at most times times in total. Only the listed exceptions are retried; any other error goes up at once. After the last failed attempt, re-raise the last error. Keep the function's name. times below 1 raises ValueError before any call.
Data and an example
The checks run after your code and can use these:
calls = []def make(outcomes, **options): """send_payout decorated with retry(**options). Each call takes the next outcome: an exception is raised, a value is returned.""" left = iter(outcomes) @retry(**options) def send_payout(payout_id): calls.append(payout_id) outcome = next(left) if isinstance(outcome, Exception): raise outcome return outcome return send_payoutdef attempts(outcomes, **options): """Calls send_payout('po_0101') once. Returns (its result or 'ErrorType: message', how many calls ran).""" calls.clear() try: result = make(outcomes, **options)("po_0101") except Exception as e: result = f"{type(e).__name__}: {e}" return result, len(calls)T = (TimeoutError,)Example: attempts([TimeoutError('slow'), TimeoutError('slow'), 'sent'], times=3, exceptions=T) → ('sent', 3)
6 checks. Your own print() output is shown too.
import functools
def retry(times, exceptions):
...
Show answer
Reference
import functools
def retry(times, exceptions): if times < 1: raise ValueError(f"times must be at least 1, got {times}")
def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): for attempt in range(1, times + 1): try: return func(*args, **kwargs) except exceptions: if attempt == times: raise # the error of the last attempt, with its traceback return wrapper return decoratorChecks and the expected values
-
attempts([TimeoutError('slow'), TimeoutError('slow'), 'sent'], times=3, exceptions=T)→('sent', 3) -
attempts([TimeoutError('try 1'), TimeoutError('try 2'), TimeoutError('try 3'), 'sent'], times=3, exceptions=T)→('TimeoutError: try 3', 3) -
attempts([ValueError('bad amount'), 'sent'], times=3, exceptions=T)→('ValueError: bad amount', 1) -
attempts([ConnectionError('reset'), TimeoutError('slow'), 'sent'], times=3, exceptions=(TimeoutError, ConnectionError))→('sent', 3) -
make(['sent'], times=1, exceptions=T).__name__→'send_payout' -
make(['sent'], times=0, exceptions=T)→raises ValueError
Three levels: retry(times, exceptions) checks its arguments and returns the decorator, the decorator receives the function, and the wrapper runs the attempts. except exceptions accepts a tuple, so only the listed errors are retried: the ValueError in the third check goes up on the first call. On the last attempt a bare raise re-raises the error that is being handled, the last one, with its traceback. Raising a saved first error would hide what happened at the end, and the second check expects try 3. range(1, times + 1) makes times the total number of calls, not the number of retries after the first call; in an interview, ask which one is meant. A real retry also waits between attempts, with backoff and jitter: see Errors and validation.
Further reading
Section titled “Further reading”- functools.wraps — what it copies, and
update_wrapperbehind it. - functools.lru_cache — the built-in cache and
cache_info(). - Function definitions — the decorator syntax and what it is equivalent to.
- The nonlocal statement — assigning to a variable of the outer function.
Related topics
Section titled “Related topics”- Classes and state — when the state grows, a small class reads better than attributes on a function.
- Caching and rate limits — a TTL cache written as a decorator with parameters and counters.
- Errors and validation — which errors a retry decorator should catch, and how long to wait.
- Time windows — another kind of state that tests drive with an injected clock.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.