Skip to main content
  1. Posts/

Common Python Pitfalls: Mutable objects

··110 words·1 min·

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 arg

Key takeaway
#

Python is an incredibly powerful language, but knowing these details helps you avoid hard-to-find bugs.

Also published on LinkedIn.
Juan Pedro Bretti Mandarano
Author
Juan Pedro Bretti Mandarano