Sub topic 10
Accepting any number of arguments with *args and **kwargs
This chapter assumes you can define a function with def, pass arguments by position and by keyword, and give parameters default values. You should also know tuples and dictionaries, because Python uses both to hold the extra arguments.
Why variable-length parameters exist
Some functions cannot know in advance how many arguments callers will pass. print accepts any number of values. A logging helper may need to forward whatever options it receives to another function. Writing def total(a, b, c, d, e) does not solve this.
Python gives you two collecting parameters:
*argsgathers extra positional arguments into a tuple.**kwargsgathers extra keyword arguments into a dictionary.
The names args and kwargs are conventions. The * and ** are what matter, and you can pick other names, such as *numbers or **options, when they describe the data better.
Collecting positional arguments with *args
A parameter with one star receives every positional argument that no earlier parameter claimed.
def total(*numbers):
return sum(numbers)
print(total()) # 0
print(total(4)) # 4
print(total(1, 2, 3)) # 6
print(type(total.__code__.co_varnames)) # <class 'tuple'>Inside the function, numbers is a tuple. It is empty when the caller passes nothing, so total() is valid and returns 0. Because it is a tuple, you can loop over it, index it, and take its length, but you cannot change it.
Collecting keyword arguments with **kwargs
A parameter with two stars receives every keyword argument that does not match a named parameter. The keys are strings and the values are whatever the caller passed.
def summarize(*args, **kwargs):
return len(args), sorted(kwargs)
print(summarize(1, 2, 3, color="red", size=5)) # (3, ['color', 'size'])Here args is (1, 2, 3) and kwargs is {"color": "red", "size": 5}. You work with kwargs like any dictionary: .items(), .get(key, default), and in all behave as usual.
Combining them with ordinary parameters
You can mix ordinary parameters, *args, keyword-only parameters, and **kwargs in one signature. The order is fixed:
- Ordinary parameters (with or without defaults)
*args- Keyword-only parameters
**kwargs
def describe(first, *args, sep="-", **kwargs):
parts = [first, *args]
text = sep.join(str(p) for p in parts)
extras = ", ".join(f"{k}={v}" for k, v in kwargs.items())
return f"{text} [{extras}]" if extras else text
print(describe("a", "b", "c")) # a-b-c
print(describe("a", "b", sep="+", x=1, y=2)) # a+b [x=1, y=2]In the second call, "a" binds to first and "b" goes into args. The keyword sep matches a named parameter, so it does not reach kwargs. The leftover x and y do.
Parameters after *args are keyword-only
Anything that follows *args can only be filled by name. This is why sep above must be written as sep="+". The same rule applies when you write a bare * with no name, which an earlier chapter covered.
def join_words(*words, sep=" "):
return sep.join(words)
print(join_words("a", "b", "c", sep="-")) # a-b-c
print(join_words("a", "b", "-")) # a b -In the second call the "-" is only another word, because no positional argument can reach sep. That is the intended behavior, but it surprises people who expected sep to be the last positional value.
Unpacking arguments at the call site
The stars also work in a call, where they do the reverse job. * spreads an iterable into positional arguments. ** spreads a mapping into keyword arguments.
def volume(length, width, height):
return length * width * height
dims = (2, 3, 4)
spec = {"length": 2, "width": 3, "height": 4}
print(volume(*dims)) # 24
print(volume(**spec)) # 24
print(volume(2, *[3, 4])) # 24You can use several unpackings in one call, and you can mix them with ordinary arguments. Python 3.5 and later allow this:
defaults = {"sep": ", "}
print(*["a", "b", "c"], **defaults) # a, b, cThe unpacked mapping must have string keys that match parameter names (or the function must accept **kwargs). Otherwise the call fails.
Forwarding arguments to another function
The most common real use of both collectors is a wrapper that passes everything along without knowing the target's signature.
def power(base, exponent=2):
return base ** exponent
def log_call(func, *args, **kwargs):
print(f"calling {func.__name__} with {args} and {kwargs}")
return func(*args, **kwargs)
print(log_call(power, 2, exponent=5))
# calling power with (2,) and {'exponent': 5}
# 32log_call never mentions base or exponent. If power gains a new parameter later, the wrapper still works. Decorators, which you will meet in later material, rely on this pattern.
Behavior worth knowing
- Each call gets a new tuple and a new dictionary. Nothing is shared between calls, so
*argsand**kwargsdo not have the mutable-default problem. - The
**kwargsdictionary is a copy of the caller's data. Changing it inside the function does not change the dictionary the caller unpacked. - The values inside are still the caller's objects. If an item is a list, mutating that list is visible outside the function.
def change(**kw):
kw["x"] = 99
return kw
original = {"x": 1}
print(change(**original)) # {'x': 99}
print(original) # {'x': 1}Common errors
| Mistake | Result |
|---|---|
| Positional argument after a keyword argument, as in `f(a=1, 2)` | `SyntaxError` |
| A parameter listed after `**kwargs` | `SyntaxError` |
| Passing a value both by position and by name | `TypeError: ... got multiple values for argument` |
| Unpacking a dictionary with non-string keys using `**` | `TypeError: keywords must be strings` |
| Unpacking two dictionaries that share a key, as in `f(**a, **b)` | `TypeError: ... got multiple values for keyword argument` |
The third row is easy to hit when mixing styles:
def volume(length, width, height):
return length * width * height
try:
volume(1, 2, 3, height=4)
except TypeError as error:
print(error) # volume() got multiple values for argument 'height'Python filled height from the third positional value, then found a keyword for the same parameter.
def connect(host, **options):
timeout = options.get("timeout", 10)
return host, timeout
print(connect("db", timout=5)) # ('db', 10)If a function reads only a known set of options, declare them as named keyword-only parameters instead, so Python rejects unknown names for you. Reserve **kwargs for cases where you forward the options on or truly accept arbitrary keys.
Choosing when to use them
Use *args when the arguments are many values of the same kind, as in total(1, 2, 3). Use **kwargs when you forward options to another callable or accept open-ended labels. Avoid both when you know the parameters. Explicit names give you better error messages, better editor help, and a signature that documents itself.
A signature such as def f(*args, **kwargs) accepts every call, so it tells the reader nothing. If you write one, explain in the docstring what is expected and where the values go.
Exercise
What does show(1, 2, a=3) print for def show(*args, **kwargs): print(args, kwargs), and what type is each of the two names inside the function?
Show answer
It prints (1, 2) {'a': 3}. Inside the function, args is a tuple and kwargs is a dictionary.
Exercise
Write a function join_all(*parts, sep=" ") that returns its string arguments joined by sep. What does join_all("x", "y", "-") return, and why?
Show answer
The definition is def join_all(*parts, sep=" "): return sep.join(parts). The call returns "x y -". The parameter sep follows *parts, so it is keyword-only. The "-" is therefore collected as a third part and the separator stays at its default, a space.
Exercise
Given def area(width, height): return width * height and size = {"width": 3, "height": 5}, how do you call area using size, and what happens if size also contains a key "depth"?
Show answer
Call area(**size), which returns 15. If size contains "depth", the call raises a TypeError for an unexpected keyword argument, because area has no depth parameter and no **kwargs to collect it.