I had a bug in my code that could be simplified to the following piece of code
class foo():
def __init__(self, bar=[]):
self.bar = bar
foo1 = foo()
foo1.bar.append(5)
foo2 = foo()
print(foo2.bar)
or even simplified more
def foo(bar=[]):
return bar
bar1 = foo()
bar1.append(5)
bar2 = foo()
print(bar2)
It happens that foo1.bar and foo2.bar in the first example, or bar1 and bar2 in the second example appear to be the same object, which is not my purpose.
My best explanation is that the default parameter '[]' is somehow associated with an unnamed variable and then passed by reference, and that this unnamed variable is somehow reused in the second function call.
Could someone explain what is exactly happening here and why it is happening? Especially in the case of a constructor, I don't see why someone would want to have this behavior.
Could someone also explain the proper pythonic way to avoid this behavior? It is for example plausible that you want to create multiple independent objects of a class that are empty by default. Off course, the actual class has more attributes than just one single list as in the example above.