
A behavior in Python that surprises even experienced developers.
🚨 Mutable Default Arguments#
Look at this code:
def test(arg = []):
arg.append(1)
return arg
print(test()) # [1]
print(test()) # [1, 1] Surprised?Why does this happen?#
The default argument arg = [] is created ONLY ONCE when the function is defined, not every time you call it. All calls to test() without an argument share the SAME list in memory.
Correct solution:
def test(arg = None):
if arg is None:
arg = []
arg.append(1)
return argKey takeaway#
Python is an incredibly powerful language, but knowing these details helps you avoid hard-to-find bugs.
Also published on LinkedIn.
