Part 05 / Topic 3 of 9
The mutable default argument trap
A default value is created once, when the function is defined. Not on every call.
So a list default is shared between calls. Use None and create a new list inside.
Real-world example: a shopping cart that should start empty for each customer.
def add_to_cart_bad(item, cart=[]):
cart.append(item)
return cart
print(add_to_cart_bad("Milk")) # ['Milk']
print(add_to_cart_bad("Bread")) # ['Milk', 'Bread'] <- surprise!
def add_to_cart(item, cart=None):
if cart is None:
cart = [] # fresh list every call
cart.append(item)
return cart
print(add_to_cart("Milk")) # ['Milk']
print(add_to_cart("Bread")) # ['Bread']
๐ Going deeper: defaults are stored on the function itself. After the two "bad" calls,
print(add_to_cart_bad.__defaults__)shows(['Milk', 'Bread'],). Numbers, strings, tuples andNoneare safe defaults because they cannot be changed in place.
Done here? The practice set for Part 5 โ 8 exercises with solutions โ is on the part page.