Sub topic 6
Forwarding Arguments in Wrappers and Decorators
This chapter assumes you can write functions with *args and **kwargs, and that you know how * and ** unpack values at a call site. It also assumes you know that a function can be passed around like any other value. Here you combine those pieces to build wrappers that work with any function.
The forwarding pattern
A wrapper is a function that calls another function and adds behavior before or after the call. The wrapper doesn't know which function it will wrap, so it can't list that function's parameters. It accepts everything with *args and **kwargs, then passes everything on with * and **.
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__} with {args} {kwargs}")
return func(*args, **kwargs)
return wrapper
@log_calls
def add(a, b=0):
return a + b
print(add(1, b=2))
# calling add with (1,) {'b': 2}
# 3The @log_calls line is shorthand for add = log_calls(add). After that line, the name add refers to wrapper, and wrapper holds the original function in func.
Why the pattern works
*args packs the positional values into a tuple. **kwargs packs the keyword values into a dictionary. When the wrapper calls func(*args, **kwargs), Python unpacks both again. Each value lands in the same slot it would have reached in a direct call.
The wrapper therefore never needs to know the original signature. It also doesn't break if the original function gains a new parameter later.
Keep the return value
A wrapper that forgets return silently turns every result into None.
def broken(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs) # result is thrown away
return wrapperCapture the result in a variable if you need to run code after the call:
import time
import functools
def timed(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:.6f}s")
return result
return wrapperPreserve the original's identity with functools.wraps
Without functools.wraps, the decorated function takes on the wrapper's metadata.
def shout(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs).upper()
return wrapper
@shout
def greet(name):
"""Return a greeting."""
return f"hello, {name}"
print(greet("ada")) # HELLO, ADA
print(greet.__name__) # wrapper
print(greet.__doc__) # NoneAdding @functools.wraps(func) above wrapper copies __name__, __doc__ and a few other attributes from func. It also sets __wrapped__, which tools such as inspect.signature follow to report the original signature. Debuggers, documentation tools and tracebacks all depend on this metadata, so make wraps a habit.
Decorators that take arguments
A decorator with its own settings needs one more layer. The outer function receives the settings and returns the real 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=2)
def say(text, end="!"):
print(text + end)
say("hi", end="?")
# hi?
# hi?Read @repeat(times=2) as two steps. First repeat(times=2) runs and returns decorator. Then decorator is applied to say. The call say("hi", end="?") reaches wrapper, which forwards both the positional and the keyword argument.
Common errors
| Mistake | Effect |
|---|---|
| `def wrapper(*args)` without `**kwargs` | Any keyword argument raises `TypeError` |
| `func(args, kwargs)` without the stars | The original receives one tuple and one dictionary as two positional arguments |
| No `return` in the wrapper | The decorated function always returns `None` |
| Omitting `functools.wraps` | The function's name and docstring are replaced by the wrapper's |
The missing stars are easy to overlook, because the code runs until the original function complains about its arguments:
def pair(a, b):
return a, b
args = (1, 2)
print(pair(*args)) # (1, 2)
try:
pair(args) # one tuple, but pair needs two arguments
except TypeError as error:
print("TypeError:", error)Exercise
Write a decorator count_calls that counts how many times the decorated function has been called, using forwarding with *args and **kwargs. Store the count in an attribute named calls on the wrapper. Keep the original name and return value.
Show answer
import functools def countcalls(func): @functools.wraps(func) def wrapper(args, kwargs): wrapper.calls += 1 return func(args, **kwargs) wrapper.calls = 0 return wrapper @countcalls def add(a, b=0): return a + b add(1) add(2, b=3) print(add.calls) # 2 print(add._name_) # add