Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Variadic positional parameters: `*args`

In a function definition, `*args` collects extra positional arguments into a tuple. In a call, `*` unpacks an iterable into positional arguments.

Version: Python 3.12

Syntax

def f(required, *args, option=False):
    ...

In Python 3.12, *args lets a function accept a variable number of positional arguments. In def f(required, *args, option=False):, it collects the positional arguments not bound to preceding parameters, in the order they were passed. Inside the function, args is a tuple, or () if there are no extras.

The name args is a convention; the * prefix marks the parameter as collecting positional arguments. Because option follows *args, it is keyword-only: pass it as option=True, for example. A bare * also introduces keyword-only parameters but does not collect positional arguments.

A single star collects positional arguments in a definition, but in a call such as func(*args, **kwargs) it unpacks an iterable into positional arguments. The wrapper uses a separate mechanism to forward keyword arguments: **kwargs collects unmatched keyword arguments into a dictionary in the definition, and ** unpacks a mapping with string keys into keyword arguments in the call. The target function's signature still applies: a missing required argument or two values for the same parameter raise TypeError.

An audit wrapper can count the arguments, forward them unchanged, and return the target's result. functools.wraps preserves metadata such as the original function's name. Avoid logging raw argument values in real audit logs: they may contain passwords or other sensitive data.

Examples

from functools import wraps


def audit(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"audit: positional={len(args)}, keyword={len(kwargs)}")
        return func(*args, **kwargs)

    return wrapper


@audit
def total(base=0, *increments, scale=1):
    return (base + sum(increments)) * scale


print(total(10, 2, 3, scale=2))
print(total())

Result

audit: positional=3, keyword=1
30
audit: positional=0, keyword=0
0

On the first call, the wrapper counts three positional arguments and one keyword argument. After forwarding, `total` binds `10` to `base`, `(2, 3)` to `increments`, and `2` to `scale`, returning `30`. The second call shows both empty collections (`()` and `{}`); the defaults give `0`.

Related lessons

  • Python · Lesson 10 · Advanced · Version: 5

Sources