Sub topic 5
Unpacking sequences and dictionaries into calls
This chapter assumes you can define and call functions, use default parameter values, work with tuples and dictionaries, and loop over a dictionary with items(). You should also know how *args and **kwargs collect extra arguments in a signature. Here you will learn the reverse operation. At a call site, * and ** spread a collection into separate arguments.
Two directions, one syntax
In a def line, *args packs extra arguments into a tuple. In a call, * does the opposite and unpacks a sequence into separate positional arguments. The same applies to ** and dictionaries.
Unpacking a sequence with *
Put * before an iterable in the call, and Python passes its items as positional arguments, in order.
def area(width, height):
return width * height
size = (3, 4)
print(area(*size)) # 12The call area(*size) behaves exactly like area(3, 4). The function cannot tell the difference.
The operand does not have to be a tuple. Any iterable works: lists, ranges, sets, strings, generators. You can also mix unpacked and plain arguments, and use * more than once.
def add3(x, y, z):
return x + y + z
print(add3(*[1, 2, 3])) # 6
print(add3(1, *[2, 3])) # 6
print(add3(*[1, 2], *(3,))) # 6
print(add3(*range(3))) # 3Arguments are assembled left to right, so the order you write is the order the function receives.
Unpacking a dictionary with **
Put ** before a mapping, and each key becomes a keyword argument name and each value becomes its value.
def describe(name, age, city="unknown"):
return f"{name}, {age}, {city}"
row = ("Ada", 36)
extra = {"city": "London"}
print(describe(*row, **extra)) # Ada, 36, London
print(describe(**{"name": "Bob", "age": 41})) # Bob, 41, unknownThe keys must be strings, and each one must match a parameter name. If the function has a **kwargs parameter, unmatched keys land there instead of failing.
Positional and keyword unpacking combine freely in one call. The * part fills positional slots first. The ** part then fills the rest by name.
What happens when the shapes do not match
Unpacking does not check anything itself. The normal argument-binding rules apply after the spread, so a mismatch produces the usual TypeError.
def area(width, height):
return width * height
try:
area(*(1, 2, 3))
except TypeError as error:
print(error) # area() takes 2 positional arguments but 3 were given
try:
area(**{"width": 1, "depth": 2})
except TypeError as error:
print(error) # area() got an unexpected keyword argument 'depth'
try:
area(**{"width": 1})
except TypeError as error:
print(error) # area() missing 1 required positional argument: 'height'Read these messages as if you had typed the expanded call by hand. That is how Python sees it.
Gotchas with * and **
Two behaviors surprise people who learned unpacking from tuples and lists alone.
A dictionary unpacked with * gives its keys
Iterating over a dictionary yields keys, so a single * spreads the keys and drops the values.
point = {"x": 1, "y": 2}
print(*point) # x y
print(*point.values()) # 1 2Use ** for keyword arguments. Use *point.values() when you want the values as positional arguments.
A generator can be unpacked only once
Unpacking consumes an iterator. After the call, nothing is left.
def add3(x, y, z):
return x + y + z
nums = (n for n in range(3))
print(add3(*nums)) # 3
print(list(nums)) # []If you need the values again, store them in a list or tuple first.
Repeated names raise an error
A parameter can receive only one value. If a positional argument and a ** key both target the same parameter, Python raises a TypeError. The same happens when two ** mappings share a key.
def greet(name):
return f"Hello, {name}"
data = {"name": "Bob"}
print(greet(**data)) # Hello, Bob
try:
greet("Ada", **data)
except TypeError as error:
print(error) # greet() got multiple values for argument 'name'
try:
greet(**{"name": "A"}, **{"name": "B"})
except TypeError as error:
print(error) # greet() got multiple values for keyword argument 'name'This differs from merging dictionaries in a literal, where the later key silently wins. A later chapter covers that case.
A practical use
Unpacking is common when data arrives as a record and the function wants named parameters. A configuration dictionary or a parsed row can go straight into a call.
def connect(host, port=5432, *, user="guest"):
return f"{user}@{host}:{port}"
config = {"host": "db.local", "port": 6543, "user": "ada"}
print(connect(**config)) # [email protected]:6543
args = ("db.local", 6543)
print(connect(*args, user="ada")) # [email protected]:6543Both calls produce the same result. The first spreads everything by name. The second spreads the positional part and names one argument directly.
Exercise
Given def volume(l, w, h): return l * w * h, dims = (2, 3) and extra = {"h": 4}, write a single call to volume that uses unpacking and returns 24. What happens if extra is changed to {"h": 4, "l": 1}?
Show answer
volume(*dims, **extra) returns 24. *dims supplies l=2 and w=3 by position, and **extra supplies h=4 by name. With {"h": 4, "l": 1}, the key l targets a parameter that already received 2 positionally, so Python raises TypeError: volume() got multiple values for argument 'l'.