0

I found what I believe it is a strange behavior. I'd like to know if it is indeed normal and I missed some important part of Python language.

Program:

class A():
    def __init__(self, items=[]):
        self.items = items

    def append(self, item):
        self.items.append(item)


a1 = A()
a2 = A()
a3 = A()

print('Before')
print('a1: %s' % a1.items)
print('a2: %s' % a2.items)
print('a3: %s' % a3.items)

a1.append('x')

print('After')
print('a1: %s' % a1.items)
print('a2: %s' % a2.items)
print('a3: %s' % a3.items)

Program output:

Before
a1: []
a2: []
a3: []
After
a1: ['x']
a2: ['x']
a3: ['x']

A new item appended to a single instance of "A" causes all instances of the same class being updated with same value.

I already solved by changing the definition of class "A" init:

class A():
    def __init__(self, items=None):
        if not items:
            items = list()
        self.items = items

but I would like to understand what is behind this behavior. Thanks in advance.

Qippur
  • 3
  • 2

1 Answers1

0

Here's a good explanation in similar question. It's much better than I could write on my own. :)

https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument

cnamejj
  • 114
  • 1
  • 3