I've ran into this behavior a couple times in Python and it's a little puzzling.
class MyClass:
def __init__(self, initial_data={}):
self.data = initial_data
instance_a = MyClass()
instance_a.data['key1'] = 'val1'
print("instance_a.data:", instance_a.data)
instance_b = MyClass()
print("instance_b.data:", instance_b.data)
With the output:
instance_a.data: {'key1': 'val1'}
instance_b.data: {'key1': 'val1'}
I would expect data
to act as an instance variable, but it looks like in this case it acts as a class variable.
Does anyone know exactly why this happens and what's the best practice to avoid it?