*args and **kwargs
Collecting however many arguments a caller passes, and unpacking a list or dict back into a call.
Overview
Collecting
def total(*args):
return sum(args)
total(1, 2, 3) gives args = (1, 2, 3). total() gives args = (). The function accepts any number of positional arguments without knowing in advance how many, and inside it args is an ordinary tuple.
Two stars do the same for keyword arguments:
def describe(**kwargs):
describe(name="ana", score=91) gives kwargs = {"name": "ana", "score": 91} — an ordinary dict.
The names are pure convention. *items and **options work identically; the stars carry the meaning. Convention is strong enough here that using different names in a general-purpose helper will raise eyebrows, but in a specific function a descriptive name often reads better.
args_kwargs.py
unpacking_calls.py
Worth knowing
*args collects extra positional arguments into a tuple; **kwargs collects extra keyword ones into a dict.*args, then **kwargs.