0

I'm defining a dictionary within a class (let's call it Thingy). Sometimes I need to use other Thingy instances as keys in the dictionary for thing1. However, if I try to add thing2 as a key with value 1 (say) to the dictionary of thing1, then thing2:1 also appears in the dict of thing2!

Please confirm if you can reproduce (python 2.7.6):

# class definition
class Thingy:
    def __init__(self, d={}):
        self.dict = d

# Test code
thing1 = Thingy()
thing2 = Thingy()
thing1.dict[thing2] = 1
print('Thing1.dict is {}'.format(thing1.dict))
print('Thing2.dict is {}'.format(thing2.dict))

gives me

Thing1.dict is {<__main__.Thingy instance at 0x7f79fdeed998>: 1}
Thing2.dict is {<__main__.Thingy instance at 0x7f79fdeed998>: 1}

even though I never changed Thing2.dict!

Zen
  • 137
  • 5

1 Answers1

1

Never use mutable objects as default parameter:

class Thingy:
    def __init__(self, d={}):
Mike Müller
  • 82,630
  • 20
  • 166
  • 161