Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

`*args` and `**kwargs`: collecting and forwarding arguments

In a function definition, `*args` collects extra positional arguments and `**kwargs` collects extra keyword arguments. In a call, the same star syntax unpacks values instead.

Version: Python 3.12

Syntax

def wrapper(*args, **kwargs):
    return target(*args, **kwargs)

def dispatch(handler, /, *args, label="items"):
    return handler(*args, label=label)

In Python 3.12, the *args/**kwargs parameters distinction starts at the function definition. *args collects positional arguments not bound to other parameters into a tuple in the order they were passed. **kwargs collects unmatched keyword arguments into a new dict. With nothing to collect, they receive () and {}, respectively. The names args and kwargs are conventions; the stars determine the behavior.

An ordinary parameter declared after *args, such as label, is keyword-only. A bare * marks the start of keyword-only parameters without collecting anything. Parameters before /, such as handler in the example, are positional-only. If present, **kwargs is the last parameter.

In a call such as target(*args, **kwargs), the operation goes the other way: * unpacks an iterable into separate positional arguments, and ** unpacks a mapping with string keys into keyword arguments. Writing the same explicit keyword twice in one call causes a compile-time SyntaxError. If ** unpacking introduces a duplicate keyword, or if a positional argument and a keyword argument both supply a value for the same parameter, the call raises TypeError at runtime.

The wrapper function collects and forwards both kinds of arguments. The dispatch function collects only extra positional arguments, accepts label separately, and calls handler. If you pass a keyword that dispatch does not accept, the forwarded call raises TypeError even though wrapper accepts it.

Examples

def render(*values, label):
    return f"{label}: {values}"


def dispatch(handler, /, *args, label="items"):
    return handler(*args, label=label)


def wrapper(*args, **kwargs):
    return dispatch(render, *args, **kwargs)


print(wrapper(3, 5, label="points"))
print(wrapper())

Result

points: (3, 5)
items: ()

On the first call, `dispatch` binds `label="points"` to `label` and collects `3` and `5` in `args`. On the second call, `wrapper` has nothing to collect, so `dispatch` uses its `"items"` default.

Related lessons

  • Python · Lesson 44 · Advanced · Version: 5

Sources