*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.

On this page

Example

#
Python
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)
Resultsaved result, you can check it
(7, 'Safari')
{'guide': 'Darwin', 'modules': 12}
[INFO] Module 3 completed
[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

#
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

#
Unpacking at the call site
Python
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))
Resultsaved result, you can check it
Emma, world 7, level 1
Jack, world 2, level 5
72 95 64
95
Positional-only and keyword-only parameters
Python
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)
Resultsaved result, you can check it
Emma: +20 EXP (task)
Jack: +15 EXP (streak)
award() takes 2 positional arguments but 3 were given
Passing arguments along
Python
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)
Resultsaved result, you can check it
Mia mia@example.com 7

Good practices

#
  • Do not overuse **kwargs in 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 like force=True, which would be unclear without a name.

Related entries

#

Spotted a mistake or missing an example? Write to us.