How it works
Defaults are evaluated once when the function is defined, so a mutable default is shared across every call.
Use an immutable sentinel as the default and create the mutable value inside the body.
Common error
A mutable default argument accumulating values between calls, which is one of the most confusing bugs in the language.
Worked example
Python
def greet(name, prefix="Hi"):
return f"{prefix}, {name}"
print(greet("Ada"))
print(greet(prefix="Hello", name="Lin"))Output
Hi, Ada
Hello, LinDefaults supply omitted arguments. Keyword arguments make the selected parameter explicit and can improve readability when several arguments have similar types.
Exercises
2.4.1 · Explain
Why is def add_item(item, values=[]) risky across calls?
Show solution
The default list is created once and reused. Mutating it can leak state into later calls. Use a None default and allocate a new list when needed.
2.4.2 · Write code
Write collect(item, values=None) that uses a new list when no list is supplied. Show two independent calls.
Show solution
Allocate the default container inside the function.
One valid solution
def collect(item, values=None):
if values is None:
values = []
values.append(item)
return values
print(collect(1))
print(collect(2))Expected output
[1]
[2]