Python Functions · Lesson 66 of 149

Python *args and **kwargs

What you will learn

  • *args: collecting any number of positional arguments into a tuple
  • **kwargs: collecting any number of keyword arguments into a dictionary
  • The order of all the kinds of parameters
  • Unpacking a list or dictionary into a call with * and **
  • Forwarding arguments to another function
  • Useful patterns, and the errors

1. *args: any number of arguments

Sometimes you do not know how many arguments a caller will give. A parameter written with a star, *nums, collects all the extra positional arguments into a tuple:

def total(*nums):
    print(nums, type(nums))
    return sum(nums)

print(total())
print(total(5))
print(total(1, 2, 3))
() <class 'tuple'>
0
(5,) <class 'tuple'>
5
(1, 2, 3) <class 'tuple'>
6
  • With no arguments, nums is an empty tuple.
  • The name args is a convention (it is short for arguments). Any name after the star works: *nums, *items.
  • Inside the function, nums is an ordinary tuple: you can loop over it, index it, and take its len. (Lesson 8.3 showed the star the other way, in assignments.)

You have used functions like this already: print(1, 2, 3), max(3, 9, 2) and sum of several values all accept any number of arguments.

Normal parameters can come before the star. They take the first arguments, and the star takes the rest:

def show(first, *rest):
    return first, rest

print(show(1))
print(show(1, 2, 3))
(1, ())
(1, (2, 3))
Quick check: what is `args` inside `def f(*args)` when you call `f("a", "b")`?

The tuple ('a', 'b').

2. **kwargs: any keyword arguments

A parameter with two stars, **kwargs, collects the extra keyword arguments into a dictionary. The names become the keys:

def info(**kw):
    return kw

print(info())
print(info(a=1, b=2))
{}
{'a': 1, 'b': 2}

The keys are always text (the names), and the values are whatever was given. This is how a function can accept options it does not know about in advance, such as the attributes of an HTML tag:

def make_tag(name, content="", **attrs):
    pairs = "".join(f' {k}="{v}"' for k, v in attrs.items())
    return f"<{name}{pairs}>{content}</{name}>"

print(make_tag("a", "link", href="http://x.org", target="_blank"))
print(make_tag("p", "hi", id="intro"))
<a href="http://x.org" target="_blank">link</a>
<p id="intro">hi</p>

Without **attrs, passing href=... would be an error. Another common job is updating a dictionary:

def update(base, **changes):
    return {**base, **changes}

print(update({"a": 1, "b": 2}, b=20, c=3))
{'a': 1, 'b': 20, 'c': 3}

3. The order of parameters

When a function has several kinds of parameters, they must come in this order:

Order Kind Example
1 normal (positional) parameters a
2 parameters with defaults b=2
3 *args *args
4 keyword-only parameters (after the star) c=10
5 **kwargs **kwargs
def f(a, b=2, *args, c=10, **kwargs):
    return a, b, args, c, kwargs

print(f(1))
print(f(1, 5, 6, 7))
print(f(1, c=3))
print(f(1, 2, 3, c=4, d=5, e=6))
(1, 2, (), 10, {})
(1, 5, (6, 7), 10, {})
(1, 2, (), 3, {})
(1, 2, (3,), 4, {'d': 5, 'e': 6})
  • f(1, 5, 6, 7): a=1, b=5, and args=(6, 7).
  • f(1, c=3): c is after the star, so it can only be given by name.
  • f(1, 2, 3, c=4, d=5, e=6): the unknown d and e land in kwargs.

Once *args has collected the positional arguments, any parameter after it is keyword-only, which is why c must be named (lesson 11.3). A bare * does the same without collecting anything:

def kwonly(*args, flag=False):
    return args, flag

print(kwonly(1, 2))
print(kwonly(1, 2, flag=True))
((1, 2), False)
((1, 2), True)

A function that has no *args or **kwargs is strict about its arguments:

def no_extra(a, b):
    return a + b

no_extra(1, 2, 3)
TypeError: no_extra() takes 2 positional arguments but 3 were given
no_extra(1, 2, c=3)
TypeError: no_extra() got an unexpected keyword argument 'c'

Only a *args and a **kwargs can absorb such extras. Python stops you from writing them in the wrong order: def bad(**kw, *a) is a SyntaxError, and so is a second * or a second **.

4. The star in a call: unpacking

In a call, a star does the opposite: it spreads a collection into separate arguments (lesson 8.3). One star for a list or tuple, two stars for a dictionary:

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

args = [1, 2]
kwargs = {"c": 5}
print(three(*args))
print(three(*args, **kwargs))
print(three(*[1], **{"b": 2}))
print(three(1, *[2, 3]))
3
8
3
6
  • three(*args) is three(1, 2).
  • three(*args, **kwargs) is three(1, 2, c=5).
  • You can mix stars with ordinary arguments, and use several stars in one call.

Familiar examples:

nums = [3, 1, 4]
print(max(*nums), min(*nums))
print(pow(*(2, 10)))
4 1
1024

A key that appears twice in the unpacked dictionaries is an error:

three(**{"a": 1}, **{"a": 9, "b": 1})
TypeError: three() got multiple values for keyword argument 'a'

The exact wording may differ between Python versions. Compare building a dictionary, where the later one wins instead: {**d1, **d2} (lesson 9.5).

5. Forwarding arguments

A very common job is a function that passes all its arguments on to another function. *args and **kwargs collect them, and the stars in the call unpack them again:

def wrapper(*args, **kwargs):
    print("calling with", args, kwargs)
    return three(*args, **kwargs)

print(wrapper(1, 2))
print(wrapper(1, b=2, c=3))
calling with (1, 2) {}
3
calling with (1,) {'b': 2, 'c': 3}
6

The wrapper does not need to know what three takes. It works for any function, and this is the heart of decorators (lesson 11.11). A general "call this function" helper looks the same:

def apply(func, *args, **kwargs):
    return func(*args, **kwargs)

print(apply(max, 3, 9, 2))
print(apply(sorted, [3, 1, 2], reverse=True))
9
[3, 2, 1]

6. Useful patterns

A function that needs at least one value

max() with no arguments is an error. A function with *args accepts zero, so require the first value as a normal parameter:

def average(first, *rest):
    nums = (first,) + rest
    return sum(nums) / len(nums)

print(average(4))
print(average(4, 8, 6))
4.0
6.0

average() fails with TypeError: average() missing 1 required positional argument: 'first', which is the message you want.

Customising output

def log(msg, *values, sep=" ", end="\n"):
    return msg + sep + sep.join(map(str, values)) + end

print(repr(log("sum:", 1, 2, 3)))
print(repr(log("x", 1, 2, sep="-", end="")))
'sum: 1 2 3\n'
'x-1-2'

This is how print itself is built: any number of values, then keyword options.

Counting what arrived

def count_args(*a, **k):
    return len(a), len(k)

print(count_args(1, 2, x=1))
print(count_args(*range(5), **{"k": 1, "j": 2}))
(2, 1)
(5, 2)

7. Use them with care

*args and **kwargs are powerful, but they hide what a function accepts. A reader (and a tool such as help) cannot see the allowed names. Prefer clear named parameters when you know them, and use *args and **kwargs for:

  • functions that truly accept any number of values (total, average, log),
  • wrappers and decorators that forward to another function,
  • passing options along to something else.

Worked example: a timing wrapper that works for any function

Write a function that calls another function with any arguments, and reports what it was called with and what it returned.

def call_and_report(func, *args, **kwargs):
    result = func(*args, **kwargs)
    shown = [repr(a) for a in args] + [f"{k}={v!r}" for k, v in kwargs.items()]
    print(f"{func.__name__}({', '.join(shown)}) -> {result!r}")
    return result

call_and_report(max, 3, 9, 2)
call_and_report(sorted, [3, 1, 2], reverse=True)
call_and_report(round, 2.567, ndigits=1)
call_and_report(len, "hello")
max(3, 9, 2) -> 9
sorted([3, 1, 2], reverse=True) -> [3, 2, 1]
round(2.567, ndigits=1) -> 2.6
len('hello') -> 5
Part Purpose
*args and **kwargs accept whatever the caller gives
func(*args, **kwargs) pass it all on, unchanged
func.__name__ the function's name (lesson 11.7)
!r shows each value as code, with quotes (lesson 4.5)

The same function reports max, sorted, round and len, which take completely different arguments. The values are made up.

Common mistakes

  • Putting parameters in the wrong order (**kwargs before *args, or a normal parameter after **kwargs).
  • Forgetting that args is a tuple (immutable) and kwargs a dictionary.
  • Forgetting the star in the call when forwarding: func(args, kwargs) passes a tuple and a dictionary as two arguments.
  • Passing the same keyword twice through unpacking.
  • Using *args when named parameters would be clearer.

Key takeaways

  • *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dictionary.
  • The order is: normal, defaults, *args, keyword-only, **kwargs.
  • In a call, *list and **dict unpack into separate arguments.
  • def wrapper(*args, **kwargs): return func(*args, **kwargs) forwards any call; it is the basis of decorators.
  • Use them for "any number of values" and forwarding; use clear named parameters otherwise.

Practice

1. Write join_words(*words) that returns the words joined with spaces.

Show answer
def join_words(*words):
    return " ".join(words)

2. What does def f(**kw): return kw give for f(a=1, b=2)?

Show answer

The dictionary {'a': 1, 'b': 2}.

3. Call three(a, b, c=0) with the list [1, 2] and the dictionary {"c": 3} using unpacking.

Show answer

three(*[1, 2], **{"c": 3}), which gives 6.

4. Why is def f(**kw, *a) a syntax error?

Show answer

**kwargs must be the last parameter. Nothing may follow it.

5. Write a function show_all(*args, **kwargs) that returns how many positional and keyword arguments it received.

Show answer
def show_all(*args, **kwargs):
    return len(args), len(kwargs)

6. What is wrong with a wrapper that calls func(args, kwargs)?

Show answer

It passes the tuple and the dictionary as two single arguments. The stars are needed to spread them: func(*args, **kwargs).