Course outline · 0% complete

0/27 lessons0%

Course overview →

*args and **kwargs

lesson 2-1 · ~12 min · 4/27

Quiz

Warm-up from lesson 1-2: what does [n for n in [3, 8, 5, 10] if n > 4] evaluate to?

Functions that take any number of arguments

This unit upgrades how you write functions themselves. Flexible signatures exist because a function often cannot know in advance how many values its caller has, and because generic wrapper code, like the decorators you will build in unit 5, must forward whatever arguments it receives without listing them. *args and **kwargs are how Python expresses both.

In Python for Beginners every function had a fixed parameter list: def greet(name, age) takes exactly two values. But look at print. You can call print(1), print(1, 2), or print(1, 2, 3). How?

Put a * before a parameter name and it collects all remaining positional arguments into a tuple:

def add_all(*nums):
    total = 0
    for n in nums:
        total += n
    return total

Inside the function, nums is just a tuple you can loop over, index, or pass to len. By convention the parameter is named args, but any name works.

Code exercise · python

Run this program. The same function handles two, four, or zero arguments, because they all land in one tuple.

**kwargs collects keyword arguments

Two stars do the same trick for keyword arguments (the name=value style you used when calling functions). They land in a dict:

def make_profile(**info):
    return info

make_profile(name="Ada", role="engineer")
# {'name': 'Ada', 'role': 'engineer'}

The stars also work in reverse when calling. * unpacks a list into separate positional arguments, ** unpacks a dict into keyword arguments:

nums = [3, 5]
print(*nums)        # same as print(3, 5)

Full signature order when you combine everything: normal params, *args, then **kwargs.

Code exercise · python

Your turn. Write describe(name, **details) that prints the name, then prints one "key: value" line per keyword argument. Loop with details.items(), which you met in Python for Beginners.

Code exercise · python

Your turn. Unpacking goes the other way too. Call area twice without typing the numbers directly: once by unpacking the dims list with *, once by unpacking the settings dict with **. Print each result.

Quiz

Inside def f(*args, **kwargs), what are the types of args and kwargs?