CKTIS / Python
The `*args` parameter: collecting positional arguments
In a function definition, `*args` collects leftover positional arguments into a tuple. In the call `fn(*args)`, the star does the reverse: it passes the tuple’s items as separate positional arguments.
Version: Python 3.12
Syntax
def wrapper(*args):
return fn(*args)In Python 3.12, the *args parameter in def wrapper(*args): collects every positional argument that wasn't bound to an earlier parameter. Inside the function, args is a local tuple that preserves the order of those arguments. If none are left, it is the empty tuple (). The name args is a convention, not a keyword: *values works the same way.
Ordinary parameters written after *args, such as scale in the example, are keyword-only. *args does not collect keyword arguments, and writing args=... does not bind a value to that tuple. A trailing **kwargs is a variadic keyword parameter: it collects extra keyword arguments rather than taking a value under its own name. Without it, an unexpected keyword argument raises TypeError.
In the call fn(*args), the star unpacks an iterable (here, the tuple) into separate positional arguments. By contrast, fn(args) passes the entire tuple as one argument. A wrapper can therefore collect arguments and forward them in the same order, but fn still determines how many arguments it accepts. Too many positional arguments will raise TypeError at the call to fn.
Examples
def fn(a=0, b=0):
return a + b
def wrapper(*args, scale=1):
print(args)
return scale * fn(*args)
print(wrapper(2, 3, scale=10))
print(wrapper())Result
(2, 3) 50 () 0
The first call prints `(2, 3)` and forwards two numbers to `fn`; `scale=10` multiplies their sum by 10. The second prints `()`, so `fn` receives no arguments and uses both defaults.
Related lessons
- Python · Lesson 43 · Advanced · Version: 5