Sub topic 11
Unpacking sequences and dicts into calls
This chapter assumes you can define functions with default values, and that you know *args and **kwargs in a definition. Here you use the same two symbols in the call, where they work in the opposite direction.
Two directions for * and **
In a definition, *args and **kwargs collect extra arguments. In a call, * and ** spread values out:
*iterablepasses each item as a separate positional argument.**mappingpasses each key and value pair as a keyword argument.
def connect(host, port=5432, *, timeout=10):
return (host, port, timeout)
args = ["db.local", 6000]
opts = {"timeout": 5}
print(connect(*args, **opts)) # ('db.local', 6000, 5)The call is equivalent to connect("db.local", 6000, timeout=5). Python expands the unpacked values first, then binds them like any other arguments.
What can be unpacked
* accepts any iterable: a list, tuple, string, range, set, or generator. A generator is consumed by the unpacking, so it is empty afterwards.
** accepts a mapping, and every key must be a string. The keys must also match parameter names, unless the function has its own **kwargs.
Combining several unpackings
A call may contain more than one * and more than one **. Positional items are added in the order written.
first = ["db.local"]
rest = (6000,)
print(connect(*first, *rest)) # ('db.local', 6000, 10)
defaults = {"timeout": 5}
overrides = {"timeout": 30}
print(connect("db.local", **{**defaults, **overrides})) # ('db.local', 5432, 30)Passing **defaults, **overrides directly would raise a TypeError, because timeout would be supplied twice. To let one dict win, merge the dicts first. The later dict in {**defaults, **overrides} overwrites the earlier one.
Forwarding arguments
The most common real use is a wrapper that accepts anything and passes it on unchanged:
def logged(func):
def wrapper(*args, **kwargs):
print("calling", func.__name__)
return func(*args, **kwargs)
return wrapper
logged_connect = logged(connect)
print(logged_connect("db.local", timeout=2))
# calling connect
# ('db.local', 5432, 2)The wrapper never needs to know the signature of connect. Defaults, keyword-only parameters, and errors all behave as if the caller had used connect directly.
Errors caused by unpacking
Unpacking cannot bypass the binding rules. Each of these calls fails:
def show(items):
for key in items:
try:
connect("db.local", **{key: 1})
except TypeError as error:
print(error)
show(["host", "retries", "port"])hostraisesconnect() got multiple values for argument 'host', because the first positional argument already filled it.retriesraisesconnect() got an unexpected keyword argument 'retries'.portsucceeds, because it is still unfilled.
Two more failures are worth knowing:
connect(**{1: "x"})raisesTypeError: keywords must be strings.connect(*5)raisesTypeErrorsaying the argument after*must be an iterable.
Exercise
Given def area(width, height=1, *, unit="cm"), dims = (3, 4), and extra = {"unit": "m"}, write one call that unpacks both and state what area receives.
Show answer
area(*dims, **extra). This is the same as area(3, 4, unit="m"), so width is 3, height is 4, and unit is "m". The dict has to be unpacked with ** because unit is keyword-only.