*args and **kwargs
Collecting any number of positional arguments into a tuple and keyword arguments into a dictionary, plus unpacking a collection at call time.
Example
#def show(*args, **kwargs):
print(args)
print(kwargs)
show(7, "Safari", guide="Darwin", modules=12)
def log(level, *messages, **context):
line = f"[{level}] " + " ".join(str(m) for m in messages)
if context:
line += " " + str(context)
print(line)
log("INFO", "Module", 3, "completed")
log("WARN", "Out of fuel", user="emma", fuel=0)Definition and usage
#A parameter with one star, conventionally *args, collects all the extra positional arguments into a tuple. A parameter with two stars, **kwargs, collects the extra keyword arguments into a dictionary. Thanks to them, a function can accept any number of arguments, just like the built-in print() or max().
What matters is the stars, not the names, so you could just as well write *scores or **options. The order in the definition is fixed: ordinary parameters, *args, keyword-only parameters, and finally **kwargs. Parameters written after *args or after a lone star * can only be given by name, and parameters before a / can only be given positionally.
The stars also work the other way, at the function call: *list spreads a collection into separate positional arguments, and **dict into keyword arguments. Combining both techniques lets you pass all the arguments along without knowing them. This is what decorators and derived classes rely on when they pass parameters to super().__init__().
Syntax
#def function(a, b=0, *args, c, d=1, **kwargs):
...
function(*values, **options)Syntax elements
#*args
tuple
The extra positional arguments collected into a tuple. When there are none, the tuple is empty.**kwargs
dict
The extra keyword arguments as a dictionary{name: value}. When there are none, the dictionary is empty.*
separator
A lone star in the definition: every parameter after it must be given by name./
separator
Parameters before the slash can only be given positionally, without a name.
More examples
#def create_account(name, world, level=1):
return f"{name}, world {world}, level {level}"
row = ["Emma", 7]
settings = {"world": 2, "level": 5}
print(create_account(*row))
print(create_account("Jack", **settings))
scores = [72, 95, 64]
print(*scores)
print(max(*scores, 80))def award(name, /, exp, *, reason="task"):
return f"{name}: +{exp} EXP ({reason})"
print(award("Emma", 20))
print(award("Jack", exp=15, reason="streak"))
try:
award("Mia", 10, "bonus")
except TypeError as error:
print(error)class User:
def __init__(self, name, email=None):
self.name = name
self.email = email
class Student(User):
def __init__(self, *args, world=1, **kwargs):
super().__init__(*args, **kwargs)
self.world = world
mia = Student("Mia", email="mia@example.com", world=7)
print(mia.name, mia.email, mia.world)Good practices
#- Do not overuse
**kwargsin ordinary functions. Explicitly listed parameters are easier to read, and the editor suggests them at the call site and catches typos. - The stars also work in literals:
[*a, *b]joins lists, and{**defaults, **options}merges dictionaries. When a key repeats, the value on the right wins. - Parameters after a lone star
*force the caller to give them by name. This is useful for flags likeforce=True, which would be unclear without a name.
Related entries
#- defDefines a function: a named block of code with parameters that you can call multiple times.
- DecoratorsFunctions that wrap other functions and add behavior to them, such as logging or permission checks. Written as @name.
- Unpacking sequencesAssigning the items of a tuple or list to several variables at once.
- super()Calls a method of the base class from inside the derived class, most often the __init__ constructor.
- dict()Creates a dictionary from key-value pairs or keyword arguments.
- tuple()Creates a tuple: an immutable sequence of items.
Spotted a mistake or missing an example? Write to us.