0

I was working on my project and encountered this strange behavior. The following code shows how to reproduce it.

class TestClass:
    def __init__(self, arr=[]):
        self.arr = arr


if __name__ == '__main__':
    for i in range(3):
        test = TestClass()
        test.arr.append('x')
        print(test.arr)

I would expect the following output:

['x']
['x']
['x']

since new TestClass instance is created inside the loop. But instead, I got:

['x']
['x', 'x']
['x', 'x', 'x']

Did I misunderstand something?

python --version output:

Python 3.6.3 :: Anaconda, Inc.
axeven
  • 166
  • 1
  • 1
  • 9

1 Answers1

1

A default value in Python is not reassigned everytime the function is called, it is assigned once and everytime you call the function you will access the same object. Thus if your default value is a mutable object such as a list or a dict, it can be mutated every call.

The common way around this is to do the following:

class TestClass:
    def __init__(self, arr=None):
        self.arr = [] if arr is None else arr
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73