Intermediate Python · Lesson 1 of 14
Functions in depth
Use default values safely, collect any number of arguments with *args and **kwargs, and force clear calls with keyword-only parameters.
In Functions: write your own commands you wrote functions with parameters, return and default values. This lesson looks at the extra tools def (functions) gives you: functions that take any number of arguments, parameters that must be named, and one famous trap with default values.
Positional and keyword arguments
A positional argument is matched by its place in the call. A keyword argument is matched by its name (nights=3). You can mix them, but positional ones always come first.
def book_room(city, nights, guests=1):
return f"{city}: {nights} nights for {guests} guest(s)"
print(book_room("Lisbon", 3))
print(book_room("Lisbon", 3, 2))
print(book_room(nights=2, city="Vienna"))
print(book_room("Rome", nights=4, guests=3))Lisbon: 3 nights for 1 guest(s) Lisbon: 3 nights for 2 guest(s) Vienna: 2 nights for 1 guest(s) Rome: 4 nights for 3 guest(s)
The mutable default trap
A default value is created once, when Python reads the def line, not each time the function runs. For numbers and strings that does not matter. For a list or a dictionary it does: every call that uses the default shares the same list.
def add_item(item, basket=[]):
basket.append(item)
return basket
print(add_item("bread"))
print(add_item("milk"))
def add_item_safe(item, basket=None):
if basket is None:
basket = []
basket.append(item)
return basket
print(add_item_safe("bread"))
print(add_item_safe("milk"))['bread'] ['bread', 'milk'] ['bread'] ['milk']
The first version remembers bread from the earlier call. The safe version uses None as the default and creates a new list inside the function: the habit to keep for any list, dictionary or set.
Any number of arguments: *args
A parameter written with a star, like *prices, collects all the extra positional arguments into a tuple. The name args is only a habit; any name works.
def total(*prices):
print("Got:", prices)
return sum(prices)
print(total(2.5, 4, 1.5))
print(total())Got: (2.5, 4, 1.5) 8.0 Got: () 0
Any number of named arguments: **kwargs
Two stars, like **details, collect the extra keyword arguments into a dictionary: each name becomes a key and each value its value.
def make_profile(name, **details):
print("Name:", name)
for key, value in details.items():
print(f" {key}: {value}")
make_profile("Amara", city="Nairobi", age=29)
make_profile("Lars")Name: Amara city: Nairobi age: 29 Name: Lars
Keyword-only parameters
Every parameter written after * (or after *args) is keyword-only: the caller must write its name. This keeps calls readable when a function has options that are easy to mix up. The full order of parameters is: normal ones, *args, keyword-only ones, then **kwargs.
def transfer(amount, *, currency="EUR", note=""):
return f"Sending {amount} {currency} {note}".strip()
print(transfer(50))
print(transfer(50, currency="USD", note="for lunch"))
try:
transfer(50, "USD")
except TypeError:
print("Error: currency must be given by name")Sending 50 EUR Sending 50 USD for lunch Error: currency must be given by name
✎ Exercise
Write average(*numbers, decimals=1) that returns the average of any number of values, rounded to decimals places. With no numbers it should return 0.
Hint: numbers is a tuple, so sum(numbers) and len(numbers) work on it. An empty tuple counts as False.
def average(*numbers, decimals=1):
# your code here
return 0
print(average(4, 5, 6))
print(average(1, 2, 2, decimals=2))
print(average())
Expected output:
5.0 1.67 0
Show a solution
def average(*numbers, decimals=1):
if not numbers:
return 0
return round(sum(numbers) / len(numbers), decimals)
print(average(4, 5, 6))
print(average(1, 2, 2, decimals=2))
print(average())5.0 1.67 0
Check yourself
1. Inside def f(*args), what kind of value is args?
*args always collects the extra positional arguments into a tuple.
2. With def f(a, *, b), which call works?
b comes after *, so it is keyword-only and must be passed as b=2.
3. Why is def f(items=[]) risky?
The default list is created once, when the function is defined, so changes to it stay between calls.