Sub topic 1
Python *args and **kwargs: Accepting and Passing Flexible Arguments
Prerequisites
This chapter assumes you can define and call Python functions, use positional and keyword arguments, set default parameter values, work with tuples and dictionaries, and iterate over dictionaries with items().
Quick recap: positional and keyword arguments
A function parameter receives a value from a function call. Positional arguments match parameters by position. Keyword arguments match parameters by name.
def describe(name, age=0):
return f"{name} is {age} years old"
print(describe("Ada", 36))
print(describe(name="Grace", age=28))
print(describe("Linus"))The first call uses two positional arguments. The second uses keyword arguments. The last uses one positional argument and the default value for age.
`*args`: accepting any number of positional arguments
In a function definition, *args collects extra positional arguments into a tuple. The name args is conventional, but the asterisk is what matters.
def total(*args):
return sum(args)
print(total(1, 2, 3)) # 6
print(total()) # 0Inside total, args is always a tuple. This lets the function accept zero or more positional values.
`**kwargs`: accepting any number of keyword arguments
In a function definition, **kwargs collects extra keyword arguments into a dictionary. Each key is the argument name, and each value is the supplied value.
def show_settings(**kwargs):
for key, value in kwargs.items():
print(f"{key}={value}")
show_settings(theme="dark", volume=8)Here, kwargs contains {"theme": "dark", "volume": 8}. The function can accept any number of named options.
Exercise
What are the types of args and kwargs in def f(*args, **kwargs): ...?
Show answer
args is a tuple, and kwargs is a dictionary.