Sub topic 8
Decorators that take arguments
A plain decorator receives only the function it wraps. Often you also want to configure it, for example "repeat this call three times" or "retry on ConnectionError". This chapter shows how to build decorators that accept their own arguments, and where such decorators usually go wrong.
This chapter assumes you can write a basic decorator that forwards *args and **kwargs, you know that @name is shorthand for func = name(func), and you use functools.wraps. If any of these is shaky, review the earlier chapters first.
Why a plain decorator is not enough
A decorator is a function that takes a function and returns a function. The @ line has room for only one callable, and Python passes the decorated function to it. There is no slot for extra values.
Python solves this by evaluating the expression after @ first and then applying whatever it returns. If that expression is a call, repeat(times=3), the call must return the real decorator. This is why a decorator that takes arguments is called a decorator factory: it builds and returns a decorator.
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 three layers
The factory has three nested functions, and each has one job.
| Layer | Name in the example | Receives | Returns | Runs |
|---|---|---|---|---|
| Outer | `repeat` | The decorator's own settings (`times`) | The decorator | Once, at the `@repeat(...)` line |
| Middle | `decorator` | The function being decorated (`func`) | The wrapper | Once, right after the outer call |
| Inner | `wrapper` | The call's arguments (`*args`, `**kwargs`) | The result of `func` | Every time the decorated function is called |
The inner function can read times and func because of closures. Both variables live in enclosing scopes, and wrapper keeps references to them after the outer functions have returned.
The desugared form
Writing out the equivalent code shows that nothing special happens:
def say(message):
print(message)
say = repeat(times=3)(say)repeat(times=3) is evaluated first and gives a decorator. That decorator is then called with say. When you are unsure how many layers you need, write the explicit form and count the calls.
Arguments are fixed at decoration time
The outer function runs once, when the decorated function is defined. The value of times is captured then and does not change on later calls. Consider this:
LIMIT = 2
@repeat(times=LIMIT)
def ping():
print("ping")
LIMIT = 5
ping() # still prints twiceIf you need a setting that can change at runtime, pass a function or an object and read it inside wrapper, so the lookup happens on each call.
A realistic example: retry
A configurable retry decorator shows more of what a factory can do. It has defaults, validates its settings early, and keeps the traceback when it gives up.
import functools
import time
def retry(attempts=3, delay=0.0, exceptions=(Exception,)):
if attempts < 1:
raise ValueError("attempts must be at least 1")
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for attempt in range(1, attempts + 1):
try:
return func(*args, **kwargs)
except exceptions as exc:
if attempt == attempts:
raise
print(f"attempt {attempt} failed: {exc}")
time.sleep(delay)
return wrapper
return decorator
calls = {"n": 0}
@retry(attempts=3, exceptions=(ConnectionError,))
def flaky():
calls["n"] += 1
if calls["n"] < 3:
raise ConnectionError("network down")
return "ok"
print(flaky())This prints two "failed" lines and then ok. Three details are worth noting:
- The validation sits in the outer function, so a bad setting raises
ValueErrorwhen the module is imported. You see the mistake at once and not on the first call, which may come much later. - A bare
raiseinsideexceptre-raises the original exception with its traceback. - The
exceptionsparameter limits which errors trigger a retry. Catching everything would hide bugs such asTypeError.
The most common mistake: forgetting the call
Compare these two lines:
@repeat(times=3) # correct: the call returns the decorator
@repeat # wrong: repeat receives the function as `times`With the second form, repeat(say) runs with times=say. It returns decorator, so the name say now refers to the middle layer and not to your function. Python reports no error at definition time. The problem shows up later: say("hello") calls decorator("hello"), which returns a wrapper function and prints nothing. Because no error is raised, this is easy to miss.
The reverse mistake also exists. If you write a plain decorator and then use it as @timer(), Python calls timer() with no function and raises TypeError: timer() missing 1 required positional argument: 'func'. That error at least fails immediately.
Making the parentheses optional
Some libraries accept both @decorator and @decorator(option=value). You can support this by letting the first parameter be the function, and making the options keyword-only with defaults:
import functools
def repeat_opt(func=None, *, times=2):
def decorator(f):
@functools.wraps(f)
def wrapper(*args, **kwargs):
result = None
for _ in range(times):
result = f(*args, **kwargs)
return result
return wrapper
if func is not None:
return decorator(func) # used as @repeat_opt
return decorator # used as @repeat_opt(times=...)
@repeat_opt
def a():
print("a")
@repeat_opt(times=3)
def b():
print("b")
a() # prints a twice
b() # prints b three timesThe * makes times keyword-only. That matters because @repeat_opt(3) would otherwise put 3 into func, and the function would then try to call 3. The keyword-only rule turns that mistake into a clear TypeError.
Reducing nesting
Three nested levels can be hard to read. Two common ways to flatten them:
- Move the real work into a normal decorator and let the factory only bind settings.
functools.partialcan do the binding:
import functools
def _log(func, *, prefix):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"{prefix}: calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
def log(prefix):
return functools.partial(_log, prefix=prefix)
@log("DEBUG")
def work():
return 1
work() # prints DEBUG: calling work- Use a class whose
__init__takes the settings and whose__call__takes the function. This is covered in the chapter on class-based decorators and is useful when the decorator needs to keep state.
Debugging checklist
When a decorator with arguments misbehaves, check these in order:
- Count the
()after the decorator name in the@line. A factory needs a call. - Print
type(decorated_function). A function from a correctly built wrapper is afunction, andwrapper.__wrapped__is your original. If you see the factory's middle layer, the call is missing. - Check that
functools.wraps(func)is on the innermostwrapper, not ondecorator. Placing it on the wrong layer leaves the wrapper's name aswrapper. - Check that the outer function returns
decoratorand the middle function returnswrapper. Returningdecorator()orwrapper()calls them too early.
Exercise
Write a decorator factory require_type(expected) that checks the first positional argument of the decorated function is an instance of expected. If not, it raises TypeError. Then say what happens if you write @require_type without parentheses above a function.
Show answer
Code:
import functools
def requiretype(expected):
def decorator(func):
@functools.wraps(func)
def wrapper(first, args, *kwargs):
if not isinstance(first, expected):
raise TypeError(f"expected {expected.name}, got {type(first).name}")
return func(first, args, *kwargs)
return wrapper
return decorator
@requiretype(int)
def double(n):
return n * 2
Calling double("a") raises TypeError. Without parentheses, require_type receives the function as expected, returns decorator, and the name now refers to decorator. Nothing fails at definition time, but calling it later returns a wrapper function instead of running your code.
Exercise
In the repeat example, which of the three layers runs every time the decorated function is called, and which runs only once?
Show answer
Only the inner wrapper runs on each call. The outer repeat and the middle decorator each run once, when the decorated function is defined.