Advanced functions and decorators · 1 / 15 Theory

Variable arguments: *args and **kwargs

Until now, each function received a fixed number of arguments. But print accepts as many as you want, and so does max(3, 9, 5). How is that done?

*args: many positional arguments

A parameter with an asterisk collects all the extra positional arguments in a tuple:

def total(*numbers):
    print(numbers)
    return sum(numbers)

print(total(1, 2, 3))
# (1, 2, 3)
# 6

print(total())
# ()
# 0

The name args is just a convention: what matters is the *. Choose a name that describes the content, such as numbers or names.

**kwargs: many keyword arguments

With two asterisks, keyword arguments are collected in a dictionary:

def record(**data):
    for key, value in data.items():
        print(f"{key}: {value}")

record(name="Ana", age=30)
# name: Ana
# age: 30

Combining them with normal parameters

The order in the definition is: normal parameters, *args, parameters with a default value and, at the end, **kwargs:

def show(title, *values, separator=", ", **extras):
    print(title, separator.join(map(str, values)), extras)

show("Grades:", 7, 9, 6, separator=" | ", course="A")
# Grades: 7 | 9 | 6 {'course': 'A'}

The parameters that come after *values can only be given by name.

Unpacking when calling

The asterisks also work the other way round: when calling a function, * expands a list and ** expands a dictionary:

def power(base, exponent):
    return base ** exponent

arguments = [2, 5]
print(power(*arguments))   # 32

options = {"base": 3, "exponent": 2}
print(power(**options))    # 9

It is very useful when the data arrives in a list (for example, with input().split()) and the function expects separate arguments.

Default values

You already know default values. When calling, you can skip the middle ones by using names:

def final_price(price, tax=21, discount=0):
    return price * (1 - discount / 100) * (1 + tax / 100)

print(final_price(100))                  # 121.0
print(round(final_price(100, discount=10), 2))     # 108.9

Practice with Sum of any amount of numbers, Grades summary, Record with keyword arguments and Final price with default values.