CKTIS / Python
Variadic parameters `*args` and `**kwargs`
In Python 3.12, `*args` collects extra positional arguments into a tuple and `**kwargs` collects unmatched keyword arguments into a dictionary. At the call site, the same symbols unpack arguments.
Version: Python 3.12
Syntax
def f(first, *args, flag=False, **kwargs):
...The phrase “variadic parameters *args” refers to collecting a variable number of positional arguments. In a function definition, *args collects positional arguments not bound to earlier parameters into a tuple, in order. **kwargs collects keyword arguments that do not match a declared parameter eligible to receive them into a new dict. With nothing to collect, the respective values are () and {}. The names args and kwargs are conventional: *items and **opts work the same way.
A parameter such as flag after *args is keyword-only: pass it as flag=True, for example. A bare * also marks the start of keyword-only parameters, but it does not collect arguments. If both collectors are present, *args comes before **kwargs, and **kwargs is last.
At a call site the direction is reversed: f(*items) expands an iterable into separate positional arguments, and f(**opts) expands a mapping with str keys into keyword arguments. Passing two values for the same parameter, or passing an unmatched keyword without a **kwargs collector, raises TypeError. In these contexts, * and ** do not mean multiplication or exponentiation.
Examples
def compute_rows(*items, label="rows"):
return label, items
def build_config(**opts):
return opts
print(compute_rows(*[10, 20], label="scores"))
print(compute_rows())
print(build_config(**{"theme": "dark"}))
print(build_config())Result
('scores', (10, 20))
('rows', ())
{'theme': 'dark'}
{}
The list supplies two positional arguments to `compute_rows`; `label` is passed separately by name. `build_config` collects `theme` in `opts`. The calls without arguments show the empty tuple and dictionary, as well as the default for `label`.
Related lessons
- Python · Lesson 18 · Intermediate · Version: 3