0

Suppose the following example:

class Example(object):

    def __init__(self, data=[]):
        self.data = data

If the data argument is not given, the instance variable shall be initialized to the default value - an empty list. But consider the following session:

>>> e = Example()
>>> print(e.data)
[]
>>> e.data.append(1)
>>> print(e.data)
[1]
>>> e = Example()
>>> print(e.data)
[1]

First, an Example instance is created without specifying the exact argument value, and thus the default is used. That's expected.

Then, the member variable is modified, and its state changes as expected.

Finally, a new instance of Example is created again, the same way as in the first case. Yet, the contents of the member variable are different - the value of the variable somehow "survived" the creation of a new instance. Why?

Is this the expected behavior? What am I doing wrong?

This particular session was done in Python 2.7, but it works the same in Python 3.3.

Thanks, Petr

Posa
  • 320
  • 3
  • 8
  • [this post](http://www.lexev.org/en/2013/python-mutable-default-arguments/) maybe helpfull – stalk Jul 11 '13 at 07:59
  • Thanks for pointing me to the explanation, I did not know what I should have looked for before writing this question. After reading the answers, however, I must confess this is the first thing where Python disappointed me. :-( – Posa Jul 11 '13 at 12:10

0 Answers0