Sub topic 10
Accepting any number of arguments with *args and **kwargs
This chapter assumes you can define functions with def, pass arguments by position and by keyword, and use default values. It also assumes you know tuples and dictionaries.
Why variable-length arguments
Sometimes you cannot know in advance how many arguments a caller will pass. Built-in print accepts any number of values. You can write functions with the same flexibility by adding two special parameters to the parameter list: *args and **kwargs.
*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dictionary.
The names args and kwargs are only conventions. The * and ** are what matter. Stick with the conventional names unless a more specific name makes the code clearer, such as *values.
Collecting extra arguments
def summarize(*args, **kwargs):
return len(args), sorted(kwargs)
print(summarize(1, 2, 3, color="red", size=5)) # (3, ['color', 'size'])Inside the function, args is (1, 2, 3) and kwargs is {"color": "red", "size": 5}. The function returns the number of positional arguments and the sorted keyword names. If the caller passes nothing extra, args is an empty tuple and kwargs is an empty dictionary. Neither is ever None.
A practical example
A function that sums any number of values is a common use of *args.
def total(*numbers, start=0):
result = start
for n in numbers:
result += n
return result
print(total()) # 0
print(total(1, 2, 3)) # 6
print(total(1, 2, 3, start=10)) # 16Any parameter that comes after *numbers can only be passed by keyword. That is why start has to be named in the call. The chapter on / and * markers covers this rule in more detail.
Unpacking arguments at the call site
The same symbols work in the opposite direction in a call. * expands a sequence into positional arguments, and ** expands a dictionary into keyword arguments.
def power(base, exponent=2):
return base ** exponent
pair = (2, 10)
options = {"base": 3, "exponent": 4}
print(power(*pair)) # 1024
print(power(**options)) # 81This is useful when arguments are already stored in a list, tuple or dictionary, for example when you read them from a configuration file.
Order in the parameter list
When you combine parameter kinds, they must appear in this order:
- Regular positional parameters
- Parameters with default values
*args- Keyword-only parameters
**kwargs
def report(title, level=1, *details, **meta):
print(title, level, details, meta)
report("Status", 2, "ok", "stable", owner="Ada")
# Status 2 ('ok', 'stable') {'owner': 'Ada'}Note that level takes the second positional value. Everything after it goes into details. So you cannot skip level and still fill details by position.
Common errors
- Wrong order in the definition.
def f(**kwargs, *args)is aSyntaxError.**kwargsmust come last. - Duplicate values. Calling
report("Status", title="X")raisesTypeErrorbecausetitlereceives two values. - Forgetting that kwargs hides typos. A function that accepts
**kwargssilently accepts a misspelled name such ascolourinstead ofcolor. Use**kwargsonly when you really need open-ended names, for example when forwarding them to another function. - Forgetting to unpack.
power(pair)passes one tuple asbase. You needpower(*pair).
Exercise
What does report("A", 5, k=1) print with the definition def report(title, level=1, *details, **meta): print(title, level, details, meta)?
Show answer
It prints A 5 () {'k': 1}. No extra positional arguments are given, so details is an empty tuple. The keyword argument k goes into meta.
Exercise
Write a function join_words(*words, sep=" ") that returns the words joined by sep. What does join_words("a", "b", sep="-") return?
Show answer
The function is def join_words(*words, sep=" "): return sep.join(words). The call returns "a-b". Because sep follows *words, it must be passed by keyword.