← Back to Python, page 1

python-0007 · Easy fresher

Explain *args and **kwargs, and show how to forward arguments to another function.

*args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict. The same symbols at a call site unpack a sequence or mapping into arguments. Together they let wrappers forward any arguments unchanged.

Full answer
python
def show(*args, sep="-", **kwargs):
    print(type(args).__name__, args, type(kwargs).__name__, kwargs, sep)

show(1, 2, color="red")
nums = [3, 4]
opts = {"size": "L"}
show(*nums, **opts)
show(5, sep="|")

def target(a, b, c=0):
    return a + b + c

def forward(*args, **kwargs):
    return target(*args, **kwargs)

print(forward(1, 2, c=3))

Output:

text
tuple (1, 2) dict {'color': 'red'} -
tuple (3, 4) dict {'size': 'L'} -
tuple (5,) dict {} |
6

Inside show, args is a tuple and kwargs is a dict. At the call show(*nums, **opts), the star operators unpack the list into positional arguments and the dict into keyword arguments. forward passes everything it receives to target, the pattern decorators use.

Rules worth knowing:

  • Order in a signature: positional parameters, *args, keyword-only parameters, **kwargs.
  • Parameters after *args (or a bare *) can only be passed by keyword, as sep shows.
  • The names args and kwargs are conventions; the stars do the work.
  • Passing the same keyword twice, once directly and once through **, raises a TypeError.
python
def show(*args, sep="-", **kwargs):
    print(type(args).__name__, args, type(kwargs).__name__, kwargs, sep)

show(1, 2, color="red")
nums = [3, 4]
opts = {"size": "L"}
show(*nums, **opts)
show(5, sep="|")

def target(a, b, c=0):
    return a + b + c

def forward(*args, **kwargs):
    return target(*args, **kwargs)

print(forward(1, 2, c=3))

Run on Python 3.13.5, twice in fresh interpreters, with identical output.

Key points

  • *args gathers positional extras as a tuple
  • **kwargs gathers keyword extras as a dict
  • Stars at a call site unpack
  • Parameters after * are keyword-only
  • Wrappers forward with *args, **kwargs

Common mistakes

  • Mutating kwargs expecting the caller to see it
  • Wrong parameter order in the signature

Follow-ups

  • What does a bare * in a signature do?
  • What is a positional-only parameter (/)?

Tips

  • Show both packing and unpacking