Beware of Mutable Default Arguments in Python
As Python developers, we often enjoy the flexibility and simplicity that the language offers. However, some features can lead to unexpected behavior if not used carefully. One such feature is mutable default arguments.
The Problem
Consider the following function:
python
def test_func(newList, myList=[]):
for t in newList:
for f in t:
myList.append(f)
return myList
print(test_func([[3, 4, 5], [6, 7, 8]])) # Outputs: [3, 4, 5, 6, 7, 8]
print(test_func([[9, 10, 11], [12, 13, 14]])) # Outputs: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
At first glance, everything seems fine. But notice what happens when the function is called a second time. Instead of getting a fresh list, myList retains the values from the previous call. This is because the default list is created once and shared across all calls to the function.
The Solution:
To avoid this issue, we can use None as the default value and initialize the list inside the function:
def test_func(newList, myList=None):
if myList is None:
myList = []
for t in newList:
for f in t:
myList.append(f)
return myList
print(test_func([[3, 4, 5], [6, 7, 8]])) # Outputs: [3, 4, 5, 6, 7, 8]
print(test_func([[9, 10, 11], [12, 13, 14]])) # Outputs: [9, 10, 11, 12, 13, 14]
By doing this, each call to test_func starts with a fresh list, avoiding the unintended side effect of sharing state across function calls.
Conclusion:
Mutable default arguments can lead to subtle bugs that are hard to track down. Always use immutable default arguments or initialize mutable ones inside the function. Happy coding!Feel free to share your thoughts or any other tips you have encountered on this topic!
Top comments (0)