Sub topic 2
*args: accepting any number of positional arguments
This chapter assumes you can define and call functions, use default parameter values, and work with tuples. Later chapters cover **kwargs, parameter order, and unpacking in calls. Here the focus is *args.
The problem *args solves
A function normally has a fixed number of parameters. Calling add(1, 2, 3) on a function defined as def add(a, b) raises a TypeError. Sometimes you want a function that accepts as many values as the caller supplies, like print or max. A starred parameter does this.
What *args collects
A parameter written with one leading * collects all extra positional arguments into a tuple.
def show(*args):
print(args, type(args))
show(1, "a", None) # (1, 'a', None) <class 'tuple'>
show() # () <class 'tuple'>Three facts follow from this example:
- The collected value is always a
tuple, never a list. You can index it, slice it, loop over it and calllen()on it, but you cannot change it. - With no extra arguments,
argsis an empty tuple(), notNone. You do not need a special case for "no arguments". - The name
argsis a convention. The*makes the parameter variadic (it accepts a variable number of arguments). You could write*numbersor*parts, and a descriptive name is usually better.
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3)) # 6
print(total()) # 0Mixing required parameters with *args
Regular parameters before the star are filled first. Whatever remains goes into the tuple.
def log(level, *messages):
for message in messages:
print(f"[{level}] {message}")
log("INFO", "started", "loading config")
# [INFO] started
# [INFO] loading configThis pattern is useful when a function needs at least one value. Compare these two designs for a "largest value" helper:
def maximum(first, *rest):
return max([first] + list(rest))
print(maximum(4, 9, 2)) # 9
# maximum() raises TypeError: missing 1 required positional argument: 'first'Because first is required, calling maximum() fails with a clear error. If you wrote def maximum(*values) instead, an empty call would reach max([]) and fail later with a less helpful ValueError.
Parameters after *args are keyword-only
Once *args has collected every remaining positional argument, no positional argument can reach a parameter written after it. Such a parameter can only be given by name. It is called keyword-only.
def join(*parts, sep="-"):
return sep.join(parts)
print(join("a", "b", "c")) # a-b-c
print(join("a", "b", "c", sep="/")) # a/b/cHere sep is never filled by a positional value. join("a", "b", "/") would treat "/" as another part. Chapter 4 covers the full ordering rules.
Passing a list does not spread it
A common mistake is passing one list to a function that expects separate values.
def total(*numbers):
return sum(numbers)
values = [1, 2, 3]
try:
print(total(values))
except TypeError as error:
print(error) # unsupported operand type(s) for +: 'int' and 'list'The call supplied one argument, the list, so numbers is ([1, 2, 3],). A tuple holding one list. sum then tries 0 + [1, 2, 3] and fails. To spread a list into separate arguments, you unpack it at the call site with total(*values). That is the subject of chapter 5.
When to use *args
Use it when the function treats the extra values as one uniform group, such as numbers to add, paths to join or messages to log. Prefer an ordinary parameter that takes a list or tuple when the caller usually already has a collection. An explicit items parameter is easier to read and to type-check, and it avoids the mistake above.
Quick reference
| Situation | Result |
|---|---|
| `def f(*args)` called as `f()` | `args == ()` |
| `def f(*args)` called as `f(1, 2)` | `args == (1, 2)` |
| `def f(a, *args)` called as `f(1, 2, 3)` | `a == 1`, `args == (2, 3)` |
| `def f(a, *args)` called as `f()` | `TypeError`, `a` is missing |
| `def f(*args, k=0)` called as `f(1, 2, k=5)` | `args == (1, 2)`, `k == 5` |
Exercise
Write a function average(first, *rest) that returns the mean of all the numbers passed to it. What does average(10) return, and what happens when you call average()?
Show answer
def average(first, *rest): numbers = [first] + list(rest) return sum(numbers) / len(numbers) average(10) returns 10.0, because rest is the empty tuple () and the list holds only 10. average() raises TypeError because the required parameter first is missing. Making first required guarantees at least one number, so the division never divides by zero.
Exercise
Given def join(*parts, sep="-"), what does join("x", "y", "+") return?
Show answer
It returns "x-y-+". All three positional values are collected into parts, and sep keeps its default "-". To use "+" as the separator you must write sep="+".