and let a function accept a of arguments. collects extra arguments into a tuple; collects extra arguments into a dict. (The names are convention — the and are what matter.)
and let a function accept a of arguments. collects extra arguments into a tuple; collects extra arguments into a dict. (The names are convention — the and are what matter.)
*args**kwargs*args**kwargs***def total(*args): # collects all positional args into a tuple
print(args) # e.g. (1, 2, 3)
return sum(args)
total(1, 2, 3) # 6
total(1, 2, 3, 4, 5) # 15 — any number of args
def configure(**kwargs): # collects keyword args into a dict
print(kwargs) # e.g. {"host": "localhost", "port": 8080}
for key, value in kwargs.items():
print(f"{key} = {value}")
configure(host="localhost", port=8080, debug=True)
def func(a, b, *args, **kwargs):
# a, b → required positional
# args → extra positional (tuple)
# kwargs → extra keyword (dict)
...
func(1, 2, 3, 4, x=5, y=6)
# a=1, b=2, args=(3, 4), kwargs={"x": 5, "y": 6}
The required order is: regular params, then *args, then **kwargs.
# `*` and `**` also UNPACK collections INTO arguments at the call site
numbers = [1, 2, 3]
total(*numbers) # same as total(1, 2, 3)
settings = {"host": "x", "port": 80}
configure(**settings) # same as configure(host="x", port=80)
The same syntax unpacks a list/dict into positional/keyword arguments — handy for forwarding arguments.
def wrapper(*args, **kwargs):
# accept ANY arguments and pass them through unchanged
return original_func(*args, **kwargs)
This pass-through pattern is how decorators and wrapper functions handle any function signature.
*args/**kwargs enable flexible function signatures that accept any number of arguments — essential for writing general-purpose utilities, wrappers, and especially decorators (which must wrap functions of unknown signatures via *args, **kwargs).
The unpacking direction (*list, **dict) is equally useful for forwarding or spreading arguments.
Understanding both collecting and unpacking is key to writing reusable, generic Python code and to reading the many library APIs and decorators that rely on these features.