Mutable Default Arguments in Python
Default arguments are only instantiated at function definition time. This means that if you assign a mutable value (such as a list, dictionary, or object) as the default value of a keyword argument to a function, then modifications to that function will persist forever. As an example, take this function:
def foo(x=[]):
x.append(1)
print(x)
You'd think that executing this function multiple times would result in the same output, but because the default value of x
is a mutable type (a list), it actually grows infinitely:
Python 3.10.12 (main, Jan 17 2025, 14:35:34) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> def foo(x=[]):
... x.append(1)
... print(x)
...
>>> foo()
[1]
>>> foo()
[1, 1]
>>> foo()
[1, 1, 1]
>>> foo()
[1, 1, 1, 1]
This can be the cause of insidious bugs where function calls from across your application can result in behavior changing in a different place elsewhere in the application.