4

The code that I'm acttualy having the problem with is very long, so I made an example that displays my problem.

I have two classes that inherit from a base-class (BaseClass). Both of these classes add some elements to self.Dict. However, they seem to cross contaminate elements. I was expecting c0.Dict to return {'class0': 0} and c1.Dict to return {'class1': 1}. However they both return {'class0': 0, 'class1': 1}. Why do they cross contaminate?

class BaseClass :
    def __init__ (self, _dict={}) :
        self.Dict = _dict

class Class0 (BaseClass) :
    def __init__ (self) :
        BaseClass.__init__(self)
        self.Dict['class0'] = 0

class Class1 (BaseClass) :
    def __init__ (self) :
        BaseClass.__init__(self)
        self.Dict['class1'] = 1

c0 = Class0()
c1 = Class1()

print c0.Dict
print c1.Dict 

1 Answer 1

9

You hit a python gotcha : mutable default arguments.

http://blog.objectmentor.com/articles/2008/05/22/pythons-mutable-default-problem

class BaseClass :
    def __init__ (self, _dict=None) :
        self.Dict = _dict or {}
Sign up to request clarification or add additional context in comments.

3 Comments

LOL, I was not expecting that. I was practically pulling my hair out trying to figure out where some strange side effects were coming from in my program. Thanks!
Also, the fix you posted fixes the problem. Thanks for the quick reply too.
yeah, I felt like you did when I hit that one, ie WTF ? (a few hours later) damn, ok...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.