Sub topic 8
Decorators that take arguments
This chapter assumes you can write a basic decorator, know the @ syntax, and use functools.wraps. It also assumes you understand closures, where an inner function remembers variables from the function that created it.
Why a plain decorator is not enough
A plain decorator receives one thing: the function to wrap. Suppose you want to choose how many times a function repeats. The number has to come from somewhere else, so you need a way to pass it in before the function arrives.
The @ line is an expression. Python evaluates it first, and whatever it returns must be a decorator. So @repeat(times=3) calls repeat with times=3, and the result of that call decorates the function below it.
Three levels of nesting
A decorator factory is a function that returns a decorator. That gives three layers:
- The outer function takes the decorator's arguments.
- The middle function takes the function being decorated.
- The inner function is the wrapper that runs on every call.
import functools
def repeat(times):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
result = None
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(times=3)
def say(message):
print(message)
say("hello") # prints hello three timesThe wrapper reads times from the outer scope through a closure. It also reads func from the middle scope.
The order of events
The factory runs once, when the function is defined. The wrapper runs on every call.
A factory with a default value
Often you want @repeat() to work without an argument. Give the parameter a default and keep the parentheses.
import functools
def retry(attempts=3, exceptions=(ValueError,)):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, attempts + 1):
try:
return func(*args, **kwargs)
except exceptions:
if attempt == attempts:
raise
return wrapper
return decorator
calls = {"n": 0}
@retry(attempts=3)
def flaky():
calls["n"] += 1
if calls["n"] < 3:
raise ValueError("not yet")
return "ok"
print(flaky()) # ok
print(calls["n"]) # 3The final attempt re-raises the exception, so a persistent failure is not hidden.
Common errors
Forgetting the parentheses. With @repeat instead of @repeat(times=3), the function say is passed as times. Nothing fails at definition time. The name say is now the decorator function, so calling say("hello") raises a TypeError because decorator expects a function but receives a string, or it silently returns a wrapper if you pass a function.
Wrong nesting depth. If you write only two levels and still call it with arguments, the decorated function becomes the argument, and the returned wrapper is not what you intended. Count the layers: arguments, function, call.
Missing functools.wraps. Put it on the innermost wrapper, which is the function that replaces the original. Without it, say.__name__ is "wrapper", which makes logs and tracebacks harder to read.
Evaluating arguments too early. Factory arguments are evaluated once, at definition time. A value such as datetime.now() passed to a factory is frozen at import time.
| Written | What Python does |
|---|---|
| `@repeat(times=3)` | Calls the factory, then applies the returned decorator |
| `@repeat` | Passes the function straight in as `times` |
| `@retry()` | Calls the factory with defaults, then applies the decorator |
Exercises
Exercise
Write a decorator factory prefix(text) so that a function returning "world" and decorated with @prefix("hello ") returns "hello world". Which of the three nested levels receives text?
Show answer
def prefix(text):
def decorator(func):
@functools.wraps(func)
def wrapper(args, kwargs):
return text + func(args, **kwargs)
return wrapper
return decorator
The outermost function, prefix, receives text. The middle decorator receives the function, and wrapper runs on each call.
Exercise
A teammate writes @retry without parentheses above a function that uses the retry factory from this chapter. What does the name of the decorated function refer to afterwards?
Show answer
It refers to the inner decorator function, because the factory received the decorated function as attempts and returned decorator. Calling it with the function's normal arguments then fails or behaves wrongly. The fix is to write @retry().