Sub topic 2
*args: Accepting Any Number of Positional Arguments
This chapter assumes you can define and call functions, and that you know positional and keyword arguments, default parameter values, tuples, and dictionaries. It covers only the packing side of *args, which is how a function receives extra positional arguments. The matching * syntax at the call site gets a short preview here and its own chapter later.
The problem *args solves
Suppose you want a total() function. With a fixed signature, you must decide the number of inputs in advance:
def total2(a, b):
return a + b
def total3(a, b, c):
return a + b + cYou could take a list instead, which works well. Sometimes, though, callers want to write total(1, 2, 3) and total(1, 2, 3, 4, 5) without building a list first. Built-ins such as print(), max(), and os.path.join() accept any number of positional arguments, and *args is how you write functions with the same behavior.
How packing works
Put a single * before a parameter name in the signature. Python collects every positional argument that no earlier parameter claimed into a tuple and binds that tuple to the name.
def total(*args):
return sum(args)
print(total(1, 2, 3)) # 6
print(total(10, 20)) # 30
print(total()) # 0Inside the function, args is an ordinary tuple. You can index it, slice it, loop over it, pass it to len(), and unpack it.
def inspect_args(*args):
print(type(args).__name__, args, len(args))
inspect_args()
inspect_args(10)
inspect_args("a", [1, 2], None)
# tuple () 0
# tuple (10,) 1
# tuple ('a', [1, 2], None) 3Three details are worth fixing in your head:
- The result is always a tuple, even when the caller passes one argument or none. With no extra arguments you get the empty tuple
(), neverNone. - The tuple is created fresh on every call. It is never shared between calls, so there is no mutable-default problem like the one you may know from
def f(x=[]). - The tuple holds references to the caller's objects, not copies. The elements themselves can still be mutable.
The name is a convention
Python only cares about the star. args is the conventional name, and readers expect it, but a descriptive name is often better when the function has a clear purpose:
def mean(first, *rest):
values = (first, *rest)
return sum(values) / len(values)
print(mean(4)) # 4.0
print(mean(2, 4, 9)) # 5.0Use plain *args when the function genuinely accepts anything, as in a wrapper that forwards arguments. Use a meaningful name such as *numbers, *paths, or *messages when the arguments have a role. The signature then documents itself.
The mean() example also shows a useful design trick. Because first is a regular parameter, calling mean() with no arguments fails immediately with a clear error:
try:
mean()
except TypeError as error:
print(error)
# mean() missing 1 required positional argument: 'first'If you wrote def mean(*values), an empty call would reach sum(values) / len(values) and fail with a ZeroDivisionError, which is a much less helpful message. Putting required values before the star expresses "at least one" in the signature.
Regular parameters come first
Parameters before *args are filled from the left. Whatever remains goes into the tuple.
def log(level, *messages, sep=" "):
text = sep.join(str(message) for message in messages)
print(f"[{level.upper()}] {text}")
log("info", "server started on port", 8080)
log("warn", "disk", "almost", "full", sep="-")
# [INFO] server started on port 8080
# [WARN] disk-almost-fullHere level takes the first argument, and messages takes the rest. The sep parameter after the star is keyword-only, which the next section explains.
A parameter with a default value can also sit before *args, but this has a cost.
def show(a, b=10, *rest):
print(a, b, rest)
show(1)
show(1, 2)
show(1, 2, 3, 4)
# 1 10 ()
# 1 2 ()
# 1 2 (3, 4)The call show(1, 2, 3, 4) binds a=1, b=2, and rest=(3, 4). Notice that you cannot send values into rest without also supplying b positionally. In that sense the default on b is not really usable once *rest is in play. If you find yourself writing this shape, consider whether b should be keyword-only instead (see below) or whether a default is helpful at all.
Parameters after *args are keyword-only
Once *args appears, any parameter written after it cannot be filled positionally, because the star would swallow every extra positional value. These parameters must be passed by name.
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 -The second call shows the effect. The "-" is just another word, because there is no way to reach sep except by name. This is the same rule print() uses for its sep and end parameters. The full rules for ordering and keyword-only parameters get their own chapters, so here you only need the idea that anything after *args is named-only.
A bare star
You can write * without a name. It does not collect anything. It only marks the start of the keyword-only parameters.
def connect(host, *, port=5432, timeout=10):
return f"{host}:{port} (timeout {timeout}s)"
print(connect("db.local", port=6543)) # db.local:6543 (timeout 10s)Compare this with *args. Both forbid extra positional values after them in the signature, but *args accepts them (and stores them), while a bare * rejects them. Calling connect("db.local", 6543) raises a TypeError.
Typical uses
Aggregating values
Functions that combine an open-ended set of values, such as total, mean, longest, or merge, are the classic fit.
def longest(first, *others):
best = first
for item in others:
if len(item) > len(best):
best = item
return best
print(longest("kiwi", "banana", "fig")) # bananaFormatting and output helpers
Wrapper functions around print() or string joining often take *parts, so callers don't need to build a list or an f-string first.
Forwarding
A function that accepts *args can hand them straight to another function. This is the foundation of decorators, covered in a later chapter. Here is a small taste:
def shout(*args):
print(*[str(a).upper() for a in args])
shout("hello", "world", 42) # HELLO WORLD 42The * in the call to print is the call-site unpacking operator. It spreads a list into separate arguments, the reverse of what the signature star does. You will use it constantly alongside *args.
Passing an existing list or tuple
If your data is already in a sequence, you must unpack it at the call. Otherwise the whole sequence becomes one single argument.
def total(*args):
return sum(args)
numbers = [1, 2, 3]
try:
total(numbers)
except TypeError as error:
print(error)
# unsupported operand type(s) for +: 'int' and 'list'
print(total(*numbers)) # 6In the failing call, args is ([1, 2, 3],), a tuple with one element that is a list. Then sum() tries 0 + [1, 2, 3] and fails. This is the single most common *args mistake, and the error message does not mention *args at all, so look at what actually arrived in the tuple when a call fails like this.
Working with the tuple
Because args is a tuple, it is read-only:
def broken(*args):
args.append(99)
try:
broken(1, 2)
except AttributeError as error:
print(error)
# 'tuple' object has no attribute 'append'If you need to change the collection, convert it, for example with values = list(args), or build a new one with sorted(args). Rebinding the name (args = args + (99,)) works but hides the original, so a new variable name is clearer.
Remember also that the tuple's elements are the caller's own objects:
def add_marker(*items):
for item in items:
item.append("x")
data = [1]
add_marker(data, data)
print(data) # [1, 'x', 'x']The tuple itself is immutable, but each element is the same list the caller passed. The function mutated it twice, because data was passed twice. This is the same aliasing behavior as for any ordinary argument, but it surprises people who expect *args to copy.
Edge cases and gotchas
- Only one
*argsper signature.def f(*a, *b)is aSyntaxError. Use two separate sequence parameters if you need two groups. - Order matters.
def f(*args, a)is legal, butais keyword-only.def f(*args, b=1, c)is also legal, because keyword-only parameters may have defaults in any order. - Iterators are consumed at the call.
total(*(x * 2 for x in range(3)))runs the generator completely to build the tuple before the function starts. A very large or infinite iterable will use a lot of memory or never finish. Use a regular iterable parameter in those cases. - Positional values cannot skip a default. As the
show(a, b=10, *rest)example illustrated, you cannot reachrestwithout supplyingb. - Introspection.
inspect.signature(total)reports the parameter as*args, and itskindisVAR_POSITIONAL. Tools and documentation generators read this, so a descriptive name helps them too. - Counting arguments.
len(args)is the number of extra positional arguments only. It does not include the regular parameters before the star.
Choosing between *args and an iterable parameter
Both approaches take many values, but they communicate different intent.
| Design | Call looks like | Best when |
|---|---|---|
| `def total(*numbers)` | `total(1, 2, 3)` | Callers usually write values inline, and the count is small and known when writing the call. |
| `def total(numbers)` | `total([1, 2, 3])` | Data already lives in a list, file, or generator, or can be large. |
| `def total(*numbers)` plus `total(*data)` | both styles work | You want both call styles, and building a tuple from `data` is acceptable. |
A practical rule is that *args is a convenience for the caller and costs one tuple allocation per call. If the data is already a collection, taking it as a normal parameter avoids copying it into a tuple and makes laziness possible.
Putting it together
Here is a small function that uses most of the ideas in this chapter: a required first value, a packed tail, and a keyword-only option.
def join_path(root, *parts, absolute=False):
pieces = [root.strip("/"), *(p.strip("/") for p in parts)]
path = "/".join(piece for piece in pieces if piece)
return "/" + path if absolute else path
print(join_path("usr", "local", "bin")) # usr/local/bin
print(join_path("/usr/", "/local/", absolute=True)) # /usr/local
print(join_path("data")) # dataWalk through the second call. The root is "/usr/", and parts is ("/local/",). Each piece is stripped of slashes, joined with /, and then prefixed with / because absolute=True was passed by name. The third call passes no extra arguments, so parts is the empty tuple and the generator yields nothing.
Exercise
What does this call print, and why? def f(a, *rest, flag=False): print(a, rest, flag) followed by f(1, 2, 3, True).
Show answer
It prints 1 (2, 3, True) False. The first argument binds to a. Every remaining positional value, including True, is packed into the tuple rest. The parameter flag comes after *rest, so it is keyword-only and can only be set as flag=True. Since it was not passed by name, it keeps its default of False.
Exercise
A colleague wrote def average(*values): return sum(values) / len(values). Calling average() raises ZeroDivisionError. Rewrite the signature so that average() fails with a clear TypeError instead, and show what average(2, 4, 9) returns.
Show answer
Use def average(first, *rest): values = (first, *rest); return sum(values) / len(values). With no arguments, Python raises TypeError: average() missing 1 required positional argument: 'first', because first is a required regular parameter. average(2, 4, 9) returns 5.0, since values is (2, 4, 9), the sum is 15, and 15 / 3 is 5.0.
Exercise
Given def total(*args): return sum(args) and nums = [1, 2, 3], why does total(nums) fail, and what is the one-character fix?
Show answer
The call passes the list as a single argument, so args is ([1, 2, 3],), and sum tries to compute 0 + [1, 2, 3], which raises a TypeError. Add a star at the call site: total(*nums). That unpacks the list into three separate positional arguments, so args becomes (1, 2, 3) and the result is 6.