Sub topic 5
Unpacking Sequences and Dictionaries into Calls
This chapter covers the call-site half of * and **. In a def line, these symbols collect extra arguments into a tuple or a dictionary. In a call, the same symbols do the opposite and spread a collection into separate arguments. I assume you can define and call functions, know positional and keyword arguments and default values, and have seen *args and **kwargs in a signature.
One idea, two directions
The two directions are easiest to keep apart if you compare them side by side.
| Where it appears | `*` does this | `**` does this |
|---|---|---|
| In a `def` signature | Packs extra positional arguments into a tuple | Packs extra keyword arguments into a dict |
| In a call | Spreads an iterable into positional arguments | Spreads a mapping into keyword arguments |
Here is the smallest example of unpacking in a call:
def area(width, height):
return width * height
size = (3, 4)
options = {"width": 2, "height": 5}
print(area(*size)) # 12
print(area(**options)) # 10
print(area(*[7], **{"height": 2})) # 14The call area(*size) behaves exactly like area(3, 4). The call area(**options) behaves exactly like area(width=2, height=5). The function never learns that unpacking happened. It receives ordinary arguments and binds them to parameters by the usual rules.
Unpacking with `*`
Any iterable works
The object after a single * can be any iterable, not only a list or a tuple.
def show(a, b, c):
print(a, b, c)
show(*[1, 2, 3]) # 1 2 3
show(*(1, 2, 3)) # 1 2 3
show(*range(3)) # 0 1 2
show(*"abc") # a b c
show(*{"x": 1, "y": 2, "z": 3}) # x y z
show(*(n * n for n in range(1, 4))) # 1 4 9Two of these results are easy to miss. A string unpacks into its characters. A dictionary unpacks into its keys, in insertion order, because iterating over a dictionary yields keys. If you want the values, write *d.values().
Mixing with ordinary arguments
You can use more than one * in a call, and you can put ordinary arguments between them:
head = [1, 2]
tail = [5, 6]
print(*head, 3, 4, *tail) # 1 2 3 4 5 6Python evaluates the arguments left to right and builds a single sequence of positional values. The callee cannot tell which values came from a literal and which came from unpacking.
The count must still match
Unpacking does not relax the signature. If the sequence has the wrong length, you get the same TypeError that a hand-written call would raise:
def pair(a, b):
return a, b
try:
pair(*[1, 2, 3])
except TypeError as error:
print(error) # pair() takes 2 positional arguments but 3 were givenIterators are consumed
An iterator can be unpacked only once. After the first unpacking it is exhausted:
numbers = iter([1, 2, 3])
print(*numbers) # 1 2 3
print(*numbers) # prints an empty line, nothing is leftA call such as f(*gen) also reads the whole generator into memory first, because Python must know every positional value before it calls the function. Do not unpack an infinite generator.
A common trap: `max(*values)`
Unpacking changes the meaning of calls to functions that accept either one iterable or several values:
values = [5]
print(max(values)) # 5
try:
print(max(*values))
except TypeError as error:
print(error) # 'int' object is not iterablemax(*[5]) is the same as max(5), and max cannot iterate over a single integer. Unpack only when the function expects separate arguments. If it already accepts an iterable, pass the iterable.
Unpacking with `**`
The mapping's keys become parameter names
** takes a mapping and turns each entry into a keyword argument. The keys must be strings, and each key must name a parameter the function can accept.
def connect(host, port=5432, *, timeout=10):
return f"{host}:{port} timeout={timeout}"
settings = {"host": "db.local", "timeout": 3}
print(connect(**settings)) # db.local:5432 timeout=3This pattern is common when settings come from a config file, a JSON payload, or a web form. You read the data into a dictionary and pass it to the function without writing every argument by hand.
Any mapping, not only `dict`
The object after ** needs a keys() method and __getitem__. Built-in dictionaries qualify, and so do other mapping types:
from collections import ChainMap
def area(width, height):
return width * height
defaults = {"width": 1, "height": 1}
chain = ChainMap({"width": 4}, defaults)
print(area(**chain)) # 4The callee gets a copy
When a function declares **kwargs, it receives a new dictionary built from the call. Changing it does not change the dictionary you unpacked:
def add_flag(**kwargs):
kwargs["debug"] = True
return kwargs
original = {"name": "app"}
result = add_flag(**original)
print(original) # {'name': 'app'}
print(result) # {'name': 'app', 'debug': True}
print(result is original) # FalseThe copy is shallow. If a value is a list, both dictionaries refer to the same list object, so mutating that list is visible on both sides. The same applies to the tuple that *args builds.
Combining both in one call
You can use * and ** together, and the unpacked values fill the same slots as ordinary arguments. Take the full signature from earlier in the tutorial:
def f(a, b=2, *args, c, d=4, **kwargs):
return a, b, args, c, d, kwargs
print(f(*[1, 2, 3], **{"c": 5, "z": 9}))
# (1, 2, (3,), 5, 4, {'z': 9})Python binds the values in this order:
- The three positional values go to
a,b, and then the surplus goes intoargs, soa=1,b=2,args=(3,). - The key
cmatches the keyword-only parameterc, soc=5. dis not supplied, so it keeps its default of4.- The key
zmatches no named parameter, so it lands inkwargs.
If a function has no **kwargs parameter, a key like z is an error instead.
Ordering rules at the call site
Positional arguments, including * unpacking, must come before ** unpacking. A positional argument after ** is a SyntaxError:
# f(**options, 1) SyntaxError: positional argument follows keyword argument unpacking
# f(**options, *values) SyntaxError: iterable argument unpacking follows keyword argument unpackingPlain keyword arguments may appear after *values, as in f(*values, c=5). Keep your calls in the order positional, then *, then keywords, then **. That order is easy to read and never trips the parser.
Useful patterns
Transposing rows into columns
zip takes several iterables as separate arguments. Unpacking a list of rows turns it into those separate arguments:
rows = [(1, "a"), (2, "b"), (3, "c")]
numbers, letters = zip(*rows)
print(numbers) # (1, 2, 3)
print(letters) # ('a', 'b', 'c')Filling a template from a dictionary
person = {"name": "Ada", "age": 36}
print("{name} is {age}".format(**person)) # Ada is 36For this specific job, "{name} is {age}".format_map(person) avoids the unpacking step. It also accepts mappings with a custom __missing__ method.
Overriding defaults safely
If you need default settings plus a few overrides, merge the dictionaries first and unpack the result once. This avoids the duplicate-key error described in the next section:
def connect(host, port=5432, *, timeout=10):
return f"{host}:{port} timeout={timeout}"
defaults = {"host": "localhost", "port": 5432}
overrides = {"port": 6432}
print(connect(**{**defaults, **overrides})) # localhost:6432 timeout=10In the merged dictionary the later port wins, so the call receives exactly one value for each name.
Pitfalls and errors
Most failures with call-site unpacking are TypeErrors raised during binding. This script triggers six of them. Each one prints a message that names the problem. The exact wording varies slightly between Python versions.
def f(a, b=0):
return a, b
cases = [
("positional and ** both set a", lambda: f(1, **{"a": 2})),
("keyword and ** both set a", lambda: f(a=1, **{"a": 2})),
("two ** both set a", lambda: f(**{"a": 1}, **{"a": 2})),
("unknown key", lambda: f(**{"a": 1, "c": 3})),
("non-string key", lambda: f(**{1: "x"})),
("nothing supplied for a", lambda: f(*[])),
]
for label, call in cases:
try:
call()
except TypeError as error:
print(f"{label}: {error}")| Mistake | Cause | Fix |
|---|---|---|
| `got multiple values for argument` | A parameter is filled both by position and by name | Remove one source, or merge dictionaries first |
| `got multiple values for keyword argument` | A name appears twice among keywords and `**` mappings | Merge with `{**a, **b}`, where the later key wins |
| `got an unexpected keyword argument` | The mapping contains a key the function does not accept | Filter the keys, or add `**kwargs` to the function |
| `keywords must be strings` | A key in the mapping is not a `str` | Convert keys with `{str(k): v for k, v in d.items()}` |
| `missing ... required positional argument` | The sequence or mapping is too short | Check the length, or give the parameter a default |
| `takes N positional arguments but M were given` | The sequence is too long | Slice it, for example `f(*seq[:2])` |
Dropping keys the function does not accept
A function without **kwargs rejects unknown keys. When you receive a larger dictionary than the function needs, you can filter it with inspect.signature:
import inspect
def connect(host, port=5432, *, timeout=10):
return f"{host}:{port} timeout={timeout}"
def call_with_known(func, options):
accepted = inspect.signature(func).parameters
return func(**{k: v for k, v in options.items() if k in accepted})
print(call_with_known(connect, {"host": "h", "verbose": True}))
# h:5432 timeout=10This helper is deliberately simple. It does not handle functions that declare their own **kwargs, which would accept every key anyway. It also does not handle positional-only parameters, which cannot be supplied by name.
Silent surprises
Some mistakes raise no error and give a wrong result:
f(*d)for a dictionarydpasses the keys, not the values, and not the pairs.f(*"hello")passes five single-character arguments, not one string.f(*some_set)passes values in an arbitrary order, so the arguments may land in the wrong parameters from one run to the next.- Unpacking a spent iterator passes nothing at all.
Summary of the rules
*iterablein a call becomes zero or more positional arguments, and**mappingbecomes zero or more keyword arguments.- Unpacking never changes the signature checks. Counts, names, and duplicates are still validated.
- Keys of an unpacked mapping must be strings that match parameter names, or land in the callee's
**kwargs. - The callee receives fresh containers, so rebinding or mutating
argsandkwargsdoes not touch your originals, although the values inside are shared. - Merge dictionaries before unpacking when you want later values to override earlier ones.
Exercise
What does the call show(*{"x": 1, "y": 2}) pass to show, and what would you write to pass the values instead?
Show answer
It passes the keys "x" and "y" as two positional arguments, because iterating over a dictionary yields its keys. To pass the values, write show(*{"x": 1, "y": 2}.values()), which passes 1 and 2.
Exercise
Given def box(width, height, depth=1): ..., base = {"width": 2, "height": 3} and extra = {"height": 4, "depth": 5}, why does box(**base, **extra) fail, and how do you write a call where extra overrides base?
Show answer
Both mappings contain the key height, so the call supplies it twice and raises a TypeError about multiple values for the keyword argument 'height'. Merge first so the later mapping wins: box(**{**base, **extra}), which calls box(width=2, height=4, depth=5).
Exercise
Write a function call_all(func, arg_lists) that calls func once for each list in arg_lists, unpacking that list into positional arguments, and returns the results as a list. Then show the result of call_all(pow, [[2, 3], [3, 2]]).
Show answer
def callall(func, arglists): return [func(*args) for args in arglists]. The call `callall(pow, [[2, 3], [3, 2]]) evaluates pow(2, 3) and pow(3, 2)`, so it returns [8, 9].