2

Can anybody explain this behaviour?

class A(object):
    def __init__(self, x={}):
        self.x = x

var1 = A()
print '#1', var1.x
var1.x['key'] = 'value'
print '#2', var1.x

var2 = A()
print '#3', var2.x

What I expect:

#1 {}
#2 {'key': 'value'}
#3 {}

What it really does:

#1 {}
#2 {'key': 'value'}
#3 {'key': 'value'}

This changes everything:

var2 = A({})
Guillermo
  • 81
  • 5
  • 1
    That's one of the most common [python gotchas](http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments) – bereal Aug 20 '14 at 09:50
  • 1
    the most asked newbie question, see http://effbot.org/zone/default-values.htm – laike9m Aug 20 '14 at 09:50
  • and I thought I was no newbee *facepalm* - it took me some time to spot this in my code – Guillermo Aug 20 '14 at 09:52
  • See also http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument – sth Aug 20 '14 at 09:58

1 Answers1

3

The default argument is instantiated once when the function is defined. Every time you assign

self.x = x

you are assigning the instance variable self.x to the same dictionary (default x). You can avoid this by putting:

def __init__(self, x=None):
   self.x = {} if x is None else x

so that a new dictionary is created each time the function is called with its default argument.

khelwood
  • 55,782
  • 14
  • 81
  • 108