Okay so this was driving me nuts all day.
Why does this happen:
class Foo:
def __init__(self, bla = {}):
self.task_defs = bla
def __str__(self):
return ''.join(str(self.task_defs))
a = Foo()
b = Foo()
a.task_defs['BAR'] = 1
print 'B is ==> %s' % str(b)
print 'A is ==> %s' % str(a)
Gives me the output:
B is ==> {'BAR': 1}
A is ==> {'BAR': 1}
I know it has to do with python passing everything by reference.
But why does this happen? This was literally making me go insane all day, basically causing me to tear my stuff apart. Shouldn’t python be smart enough to deal with something like this?
Since you have
blainitially set to a mutable type (in this case a dict) in the arguments, it gets shared sincebladoesn’t get reinitialized to a new dict instance for each instance created forFoo. Here, try this instead: