Sub topic 3
Forwarding Arguments with *args and **kwargs
This chapter assumes you can define functions with positional and keyword arguments, and that you have read the earlier chapters on functions as objects and closures.
Why forwarding matters
A decorator replaces a function with a wrapper. Callers pass their arguments to the wrapper, so the wrapper has to hand them to the original function unchanged. The wrapper cannot know in advance how many arguments the original takes or what they are called. Python solves this with *args and **kwargs.
Packing: collecting arguments in a definition
In a function definition, *args collects any extra positional arguments into a tuple. **kwargs collects any extra keyword arguments into a dictionary. The names args and kwargs are conventions. The * and ** are what matter.
def show(*args, **kwargs):
print(args)
print(kwargs)
show(1, 2, color="red")
# (1, 2)
# {'color': 'red'}A function declared this way accepts any call, including show() with no arguments.
Unpacking: spreading arguments in a call
The same symbols work in the opposite direction at a call site. * spreads a sequence into positional arguments. ** spreads a dictionary into keyword arguments.
def describe(name, age, city="Oslo"):
return f"{name}, {age}, {city}"
values = ("Ada", 36)
options = {"city": "London"}
print(describe(*values, **options)) # Ada, 36, London| Position | Symbol | What it does |
|---|---|---|
| In a `def` | `*args` | Packs extra positional arguments into a tuple |
| In a `def` | `**kwargs` | Packs extra keyword arguments into a dict |
| In a call | `*seq` | Unpacks a sequence into positional arguments |
| In a call | `**mapping` | Unpacks a dict into keyword arguments |
Putting both together
Packing in the definition and unpacking in the call gives a function that passes everything along. The function below logs a call and then runs the function it was given.
def describe(name, age, city="Oslo"):
return f"{name}, {age}, {city}"
def call_logged(func, *args, **kwargs):
print("args:", args, "kwargs:", kwargs)
return func(*args, **kwargs)
print(call_logged(describe, "Ada", 36, city="London"))
# args: ('Ada', 36) kwargs: {'city': 'London'}
# Ada, 36, LondonTwo details make this work as a stand-in for the original call. The arguments are forwarded with the same * and ** that collected them. The result is returned, so the caller sees the same value as before.
Parameter order
When a definition mixes parameter kinds, they must appear in this order: regular parameters, then *args, then keyword-only parameters, then **kwargs. A wrapper that only forwards usually needs just *args, **kwargs.
Common errors
- Forgetting
return. If the forwarding function callsfunc(*args, **kwargs)without returning the result, every call quietly returnsNone. - Passing the tuple instead of unpacking it.
func(args, kwargs)sends two arguments, a tuple and a dict.func(*args, **kwargs)sends the original arguments. - Dropping keyword arguments. A wrapper defined as
def wrapper(*args)raises aTypeErroras soon as a caller passescity="London". - Expecting a copy.
argsis a new tuple andkwargsis a new dict, but the objects inside them are the same objects the caller passed. Mutating a list insideargschanges the caller's list.
The next chapters build on this pattern. A decorator's inner function is a closure that takes *args, **kwargs and forwards them.
Exercise
What does f(1, 2, x=3) return for def f(*args, **kwargs): return len(args), len(kwargs), and what happens if f is called as f(*[1, 2], **{"x": 3})?
Show answer
Both calls return (2, 1). The first call packs 1, 2 into args and x=3 into kwargs. The second call unpacks the list and dict into the same positional and keyword arguments, so f sees an identical call.
Exercise
This function should run func and return its result, but callers always get None. What is the bug, and how do you fix it?
def run(func, args, kwargs):
func(args, **kwargs)
Show answer
The result of func(*args, **kwargs) is discarded because there is no return. Change the last line to return func(*args, **kwargs).