Sub topic 3
The Mutable Default Argument Pitfall
Assume you know variables, lists, dictionaries, if statements, and basic function calls. In this chapter, you will examine how Python evaluates function parameters and how to design clearer function interfaces.
Avoiding mutable default arguments
A default parameter value is evaluated once, when Python creates the function. If that value is mutable, such as a list or dictionary, every call without an explicit argument can share the same object.
def add_item_bad(item, items=[]):
items.append(item)
return items
print(add_item_bad("a")) # ['a']
print(add_item_bad("b")) # ['a', 'b']Use None as the default, then create a new list inside the function.
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item("a")) # ['a']
print(add_item("b")) # ['b']Accepting variable numbers of arguments
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary.
def summarize(*args, **kwargs):
return len(args), sorted(kwargs)
print(summarize(1, 2, 3, color="red", size=5))
# (3, ['color', 'size'])Controlling argument syntax
Place / after positional-only parameters. Place * before keyword-only parameters.
def clamp(value, /, low=0, *, high=100):
return max(low, min(value, high))
print(clamp(150, high=120)) # 120Here, value must be positional, while high must use its keyword.
Results, state, and documentation
return sends a value to the caller. A side effect changes something outside the function, such as a list passed by the caller. A function can do either, or both. A function with no return statement returns None.
Type hints document expected types, but Python does not enforce them automatically. A docstring explains the function's purpose and errors.
def average(values: list[float]) -> float:
"""Return the mean of values.
Raises ValueError when values is empty.
"""
if not values:
raise ValueError("values must not be empty")
return sum(values) / len(values)
print(average([2.0, 4.0, 6.0])) # 4.0Exercise
Why does add_item_bad("b") see the item from the earlier call, and how should you fix it?
Show answer
The list default is created once and reused. Use None as the default and create a new list inside the function.