The mutable default trap
Not met yet
A default value is made once, when Python runs the def line, not on every call. If the default is a list or dictionary and the function changes it, every later call sees the changes. Default to None and make a new list inside the function instead.
Try it
main.pydef add_order(item, basket=[]):
basket.append(item)
return basket
print(add_order("bread"))
print(add_order("buns"))
Output
Press Run and what your program prints shows up here.
Easy to get wrong
- Thinks a default list or dictionary is made fresh on every call, rather than once when the def line runs.
- Thinks the None-then-new-list pattern still shares one list between calls.