Mutable Default Arguments Are Shared Between Calls in Python
Default argument values are evaluated once, when the def statement runs, not on every call. A mutable default such as [] is therefore the same object on every call, and changes to it pile up.
>>> def foo(s=[]):
... s.append(1)
... return s
...
>>> foo()
[1]
>>> foo()
[1, 1]
-
The usual fix is a
Nonesentinel, creating the fresh object inside the function:def foo(s=None): if s is None: s = [] s.append(1) return s -
The defaults live on the function object, in
foo.__defaults__, which is why they persist between calls. -
Immutable defaults (
0,"",None, tuples) are safe: they can’t be changed in place.