Sub topic 3
Forwarding arguments with *args and **kwargs
This chapter assumes you can define and call Python functions, and that you know the difference between positional and keyword arguments. It covers how a decorator's wrapper accepts any call and passes it on unchanged. You will also see where that forwarding goes wrong.
Why wrappers need a flexible signature
A decorator returns a new function, the wrapper, that replaces the original. Callers now call the wrapper. If the wrapper accepts fewer arguments than the original, existing calls break.
def broken(func):
def wrapper():
return func()
return wrapper
@broken
def add(a, b):
return a + b
try:
add(1, 2)
except TypeError as error:
print(error) # broken.<locals>.wrapper() takes 0 positional arguments but 2 were givenYou could copy the original parameter list into the wrapper. That ties the decorator to one function. A decorator like timer should work on any function, so the wrapper must accept any call and hand it to the original unchanged. The tools for that are *args and **kwargs.
Packing: collecting arguments in a definition
In a function definition, *args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary. The names args and kwargs are conventions. The stars are what matter.
def show(*args, **kwargs):
print(args, kwargs)
show() # () {}
show(1, 2) # (1, 2) {}
show(1, 2, color="red") # (1, 2) {'color': 'red'}A signature of (*args, **kwargs) accepts every possible call. Python also builds a new tuple and a new dictionary on each call, so changing them never affects the caller's variables.
Unpacking: spreading arguments in a call
In a call, the stars work in reverse. *sequence spreads items as positional arguments. **mapping spreads key-value pairs as keyword arguments.
def add(a, b, c=0):
return a + b + c
numbers = (1, 2)
options = {"c": 10}
print(add(*numbers, **options)) # 13
print(add(*numbers)) # 3| Position | Syntax | Meaning |
|---|---|---|
| In a `def` | `*args` | Collect extra positional arguments into a tuple |
| In a `def` | `**kwargs` | Collect extra keyword arguments into a dict |
| In a call | `*items` | Spread an iterable as positional arguments |
| In a call | `**pairs` | Spread a mapping as keyword arguments |
A decorator uses both halves. The wrapper's definition packs whatever it receives, and the call to the original unpacks it again.
The forwarding wrapper
The pattern has three parts: accept everything, call the original with everything, and return its result.
import functools
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"calling {func.__name__} with args={args} kwargs={kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result!r}")
return result
return wrapper
@log_calls
def add(a, b=0):
return a + b
add(1, 2)
add(5, b=7)
add(b=3, a=4)The output shows each call as the caller wrote it:
calling add with args=(1, 2) kwargs={}
add returned 3
calling add with args=(5,) kwargs={'b': 7}
add returned 12
calling add with args=() kwargs={'a': 4, 'b': 3}
add returned 7The wrapper does not know whether a value arrived by position or by name. It passes each one the same way it received it, so the original function sees the call it would have seen without the decorator.
Returning the result
The wrapper must return what the original returned. Forgetting this is the most common mistake in a first decorator.
def forgetful(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs) # result is discarded
return wrapper
@forgetful
def square(x):
return x * x
print(square(4)) # NoneThe call runs and computes 16, then throws the value away. The wrapper has no return, so Python returns None.
When the extra behavior must run after the call, as in the timer from the topic plan, store the result in a variable first. A try/finally block is another option, because return inside try still lets finally run:
import functools
import time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return func(*args, **kwargs)
finally:
elapsed = time.perf_counter() - start
print(f"{func.__name__} took {elapsed:.4f}s")
return wrapperForgetting the stars in the call
The wrapper's definition needs the stars, and so does the call inside it. Without them, the tuple and dictionary are passed as two ordinary arguments.
def wrong(func):
def wrapper(*args, **kwargs):
return func(args, kwargs) # missing * and **
return wrapper
@wrong
def add(a, b):
return a + b
print(add(1, 2)) # ((1, 2) + {}) raises TypeErrorHere func receives a=(1, 2) and b={}. Adding a tuple to a dictionary raises TypeError. If the original function accepts any types, the bug can be silent: it runs with the wrong values and produces odd output instead of an error.
Inspecting and changing arguments
Because the wrapper holds the arguments before the original sees them, it can read or change them. args is a tuple, so it is immutable. kwargs is a fresh dictionary, so you can edit it safely.
import functools
def with_verbose(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
kwargs.setdefault("verbose", True)
return func(*args, **kwargs)
return wrapper
@with_verbose
def process(item, verbose=False):
return f"{item} verbose={verbose}"
print(process("a")) # a verbose=True
print(process("b", verbose=False)) # b verbose=Falsesetdefault adds the keyword only when the caller did not supply it, so explicit choices still win.
To replace a positional argument, build a new tuple, for example args = (args[0].strip(),) + args[1:].
The positional-versus-keyword trap
Suppose a decorator checks that the first argument is not negative. The obvious version looks at args[0].
def positive_first(func):
def wrapper(*args, **kwargs):
if args[0] < 0:
raise ValueError("first argument must be non-negative")
return func(*args, **kwargs)
return wrapper
@positive_first
def root(x):
return x ** 0.5
print(root(9)) # 3.0
# root(x=9) raises IndexError: tuple index out of rangeCalling root(x=9) puts x in kwargs, so args is empty and args[0] fails. The wrapper must handle both call styles. The inspect module can match the arguments to the original parameter names:
import functools
import inspect
def non_negative(func):
signature = inspect.signature(func)
@functools.wraps(func)
def wrapper(*args, **kwargs):
bound = signature.bind(*args, **kwargs)
for name, value in bound.arguments.items():
if value < 0:
raise ValueError(f"{name} must be non-negative, got {value}")
return func(*args, **kwargs)
return wrapper
@non_negative
def area(width, height):
return width * height
print(area(3, 4)) # 12
print(area(height=2, width=5)) # 10
try:
area(3, height=-1)
except ValueError as error:
print(error) # height must be non-negative, got -1signature.bind maps every argument to its parameter name, whether it came by position or by keyword. It also raises TypeError for a bad call, such as a missing argument, with a message close to Python's own. Values left to defaults do not appear in bound.arguments unless you call bound.apply_defaults() first.
What the wrapper hides
The wrapper's own signature is (*args, **kwargs), so help tools cannot see the original parameters. functools.wraps copies the name and docstring and sets a __wrapped__ attribute pointing to the original. inspect.signature follows __wrapped__, so it reports the original parameters:
import functools
import inspect
def passthrough(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
@passthrough
def connect(host, port=5432, *, timeout=10):
"""Open a connection."""
print(inspect.signature(connect)) # (host, port=5432, *, timeout=10)
print(connect.__name__) # connect
print(connect.__wrapped__) # the undecorated functionThis is a report only. The wrapper still accepts anything, and a bad call fails when the original runs, not at the wrapper. The traceback then includes a wrapper frame. The next chapters cover functools.wraps and debugging in detail.
Summary of rules
- Define the wrapper as
def wrapper(*args, **kwargs)unless the decorator is meant for one fixed signature. - Call the original as
func(*args, **kwargs), with both sets of stars. - Return the original's result, or keep it in a variable so you can act after the call.
- Do not index into
argsto find a named parameter. Useinspect.signature(func).bindwhen you need names. - Treat
argsas read-only. Editkwargsor build a new tuple.
Exercise
A decorator's wrapper is defined as def wrapper(*args, **kwargs): and calls return func(args, kwargs). The decorated function is def add(a, b): return a + b. What goes wrong when you call add(1, 2), and what is the fix?
Show answer
Without stars, func receives the tuple (1, 2) as a and the empty dict {} as b, not the values 1 and 2. The expression (1, 2) + {} raises TypeError. The fix is return func(*args, **kwargs), which unpacks the tuple into positional arguments and the dict into keyword arguments.
Exercise
Write a decorator cap_first that makes sure the parameter named count of the decorated function never exceeds 100 (replace larger values with 100), whether the caller passes it by position or by keyword. Use inspect.signature. Then decorate def repeat_word(word, count): return word * count and say what repeat_word("a", 500) returns.
Show answer
One solution:
import functools
import inspect
def capfirst(func):
signature = inspect.signature(func)
@functools.wraps(func)
def wrapper(args, kwargs):
bound = signature.bind(args, kwargs)
if "count" in bound.arguments and bound.arguments["count"] > 100:
bound.arguments["count"] = 100
return func(*bound.args, bound.kwargs)
return wrapper
Using bound.args and bound.kwargs forwards the edited values in the form the original expects. `repeatword("a", 500)` returns "a" repeated 100 times, a string of length 100.