Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I have this code
class Test(object):
def __init__(self, var1=[]):
self._var1 = var1
t1 = Test()
t2 = Test()
t1._var1.append([1])
print t2._var1
and I get “[[1]]” as the result. So clearly t1._var1 and t2._var1 are addressing the same list. If I put
t3 = Test()
print t3._var1
then I get “[[1]]” as well. So var1=[] seems to permanently bind var1 to the some list. I tried copying the list,
def __init__(self, var1=copy([])):
but got the same result, so the expression for the named argument appears to be evaluated prior to init being called, and it just gave var1 a copy of the empty list which was then shared amongst the instances.
So how do I use [] as a default value for a named argument?
You can’t use
[]directly if you want each object to have an empty list. I tend to use a work around:Naturally this won’t work if
var1can beNone, you would need to use a different object.