Sub topic 11
Unpacking sequences and dicts into calls
This chapter assumes you can define and call functions, know how positional and keyword arguments bind to parameters, and know what default values, *args and **kwargs do in a def. Here you will use * and ** on the calling side, where they spread a collection into separate arguments.
Two operators, two directions
In a def, *args and **kwargs collect extra arguments into a tuple and a dict. In a call, the same symbols do the reverse:
*iterableexpands the items of any iterable into separate positional arguments.**mappingexpands the key/value pairs of a mapping into separate keyword arguments.
def connect(host, port=5432, *, timeout=10, ssl=True):
return (host, port, timeout, ssl)
args = ["db.local", 6000]
opts = {"timeout": 5, "ssl": False}
print(connect(*args, **opts)) # ('db.local', 6000, 5, False)The call connect(*args, **opts) is the same as connect("db.local", 6000, timeout=5, ssl=False). Python expands both before it binds anything to parameters. The function cannot tell which form you used.
Defaults still apply to anything the expansion does not supply. The dict does not need a key for every parameter:
print(connect(*["db.local"], **{"ssl": False})) # ('db.local', 5432, 10, False)What `*` accepts
The operand of * can be any iterable: a list, tuple, string, set, generator, or range. Python reads it from start to end and turns each item into one positional argument.
def show(a, b, c, d):
return (a, b, c, d)
print(show(*range(4))) # (0, 1, 2, 3)
print(show(*"wxyz")) # ('w', 'x', 'y', 'z')
print(show(*(n * n for n in range(4)))) # (0, 1, 4, 9)Two consequences follow:
- A generator is consumed by the call. If you pass it again, it is empty.
- A dict used with a single
*supplies its keys, because iterating a dict yields keys.show(*{"a": 1, "b": 2, "c": 3, "d": 4})returns('a', 'b', 'c', 'd'). Use**if you want the values bound by name.
A common use of * is passing a list of rows to a function that takes several sequences:
rows = [(1, 2), (3, 4), (5, 6)]
print(list(zip(*rows))) # [(1, 3, 5), (2, 4, 6)]What `**` accepts
The operand of ** must be a mapping, meaning an object with keys() and __getitem__. A dict is the usual choice. Every key must be a string, because keys become parameter names.
Python copies the pairs into a new keyword dictionary. When the callee collects them with **kwargs, it receives its own dict. Changing kwargs inside the function never changes the caller's dict. The values are shared, though, so mutating a list stored in the dict is visible to both sides.
def mutate(**kw):
kw["x"] = 99
kw["tags"].append("seen")
d = {"x": 1, "tags": []}
mutate(**d)
print(d) # {'x': 1, 'tags': ['seen']}Mixing and repeating expansions
Since Python 3.5 you can use several * and ** expansions in one call, and put ordinary arguments between them:
def show(a, b, c, d):
return (a, b, c, d)
print(show(*[1, 2], *(3,), 4)) # (1, 2, 3, 4)
print(show(0, *[1, 2], 3)) # (0, 1, 2, 3)The ordering rules are:
- Positional arguments and
*expansions can be interleaved. Their order is the order of the final positional list. - A
*expansion may appear after an explicit keyword argument such asf(x=1, *rest). It still contributes positional arguments. Positional values are bound first, whatever the source order. - A
*expansion may not appear after a**expansion.f(**d, *a)is aSyntaxError. - Explicit keywords and
**expansions can be mixed in any order, such asf(**d, x=1).
The diagram shows the order in which Python processes a call.
Duplicate keys: merge first
If two sources supply the same keyword, the call fails. It does not let the later one win:
defaults = {"timeout": 10, "ssl": True}
overrides = {"timeout": 2}
# connect("db.local", **defaults, **overrides)
# TypeError: connect() got multiple values for keyword argument 'timeout'
merged = {**defaults, **overrides}
print(connect("db.local", **merged)) # ('db.local', 5432, 2, True)The {**a, **b} form builds a dict in which later keys overwrite earlier ones. It is the usual way to layer overrides on top of defaults before making the call. On Python 3.9 and later, defaults | overrides does the same.
Forwarding arguments
Unpacking and *args/**kwargs are used together in wrappers, such as decorators. They pass every argument through without knowing the wrapped function's signature:
def logged(func):
def wrapper(*args, **kwargs):
print("calling", func.__name__, args, kwargs)
return func(*args, **kwargs)
return wrapper
@logged
def connect(host, port=5432, *, timeout=10, ssl=True):
return (host, port, timeout, ssl)
print(connect("db.local", timeout=5))
# calling connect ('db.local',) {'timeout': 5}
# ('db.local', 5432, 5, True)Defaults stay in the wrapped function. The wrapper does not repeat them, so it only forwards what the caller actually supplied. This matters because a default is not the same as an explicit value. If a wrapper declared timeout=None and always forwarded it, the callee would receive None instead of using its own default of 10.
The same problem appears when you build a dict of options from user input. Filter out the unset entries before unpacking, so the callee's defaults apply:
raw = {"timeout": None, "ssl": False}
clean = {k: v for k, v in raw.items() if v is not None}
print(connect("db.local", **clean)) # ('db.local', 5432, 10, False)This filtering also keeps the None sentinel pattern working. A parameter written as items=None means "not supplied", so passing None explicitly and omitting the argument end up in the same branch of the function.
Reading the errors
Most unpacking failures are ordinary binding errors, with the message naming the parameter. The table lists the common ones.
| Call | Error | Cause |
|---|---|---|
| `connect(*["h"], host="x")` | `got multiple values for argument 'host'` | The positional expansion already bound `host`. |
| `connect(**{"host": "h", "color": "red"})` | `got an unexpected keyword argument 'color'` | The dict has a key with no matching parameter. |
| `connect(*[1, 2, 3])` | `takes from 1 to 2 positional arguments but 3 were given` | Extra positionals cannot reach the keyword-only parameters. |
| `connect(*5)` | `argument after * must be an iterable, not int` | The operand cannot be iterated. |
| `connect(**[1])` | `argument after ** must be a mapping, not list` | The operand is not a mapping. |
| `connect(**{1: 2})` | `keywords must be strings` | A key is not a string. |
The first row is the one that surprises people. Because positionals are bound before keywords, f(a=1, *[2]) gives 2 to the first parameter. If that parameter is a, you get a collision, even though a=1 was written first.
Summary of the rules
*xexpands any iterable into positional arguments.**mexpands a mapping with string keys into keyword arguments.- Several expansions can appear in one call, but
*may not follow**. - Positionals bind first, then keywords. A name bound twice is a
TypeError. - Duplicate keys across
**expansions are an error. Merge the dicts with{**a, **b}instead. - Defaults fill any parameter the expansions leave unbound. Drop unset entries before unpacking so defaults are not overridden by
None.
Exercise
Given def show(a, b, c, d): return (a, b, c, d), what does show(*{"a": 1, "b": 2}, 3, 4) return, and what would change if you wrote **{"a": 1, "b": 2} followed by the values 3 and 4 as positional arguments?
Show answer
The call returns ('a', 'b', 3, 4). A single * on a dict expands its keys, so a receives the string 'a' and b receives 'b', and 3 and 4 fill c and d. With ** the call must be written show(3, 4, **{"a": 1, "b": 2}), and it raises TypeError: show() got multiple values for argument 'a'. The positionals 3 and 4 bind to a and b first, so the keywords a and b collide with them.
Exercise
defaults = {"timeout": 10} and overrides = {"timeout": 2}. Why does connect("db.local", **defaults, **overrides) fail, and how do you rewrite it so the override wins?
Show answer
Both expansions supply the keyword timeout, and Python raises TypeError: connect() got multiple values for keyword argument 'timeout' instead of letting the later one win. Merge first: connect("db.local", **{**defaults, **overrides}). In the merged dict the later key overwrites the earlier one, so timeout is 2.