I stepped into a feature of python very dangerous to my style of programming. I wondered what pattern would be best to resolve these conflicts. The follwoing example should give a good insight
class TestObject():
def __init__(self, dt = {}):
self.dt = dt
def update_dt(self, new_dt):
for k, v in new_dt.items():
self.dt[k] = v
def main():
first = {'a': 1}
d1 = TestObject()
print(TestObject().__dict__)
d1.update_dt(first)
print(TestObject().__dict__)
To my surprise the last print statement returned {'dt': {'a': 1}}
and not {}
. While I was baffled at first, I think I now understand what happens. By 'updating' the self.dt
I am not only changing the attribute of object d1
but also the parameter dt
of the class.
My solution would be to never specify the default parameter as a list, dict or similar (unless this feature is wanted) and always use None instead, i.e.
def __init__(self, dt = None):
if dt is None:
dt = {}
self.dt = dt
But is there a more elegant way to tackle this 'problem'?