Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I’m finding that dictionary arguments to the init() function of my class are defaulting to values I’ve previously set in previous instances. I really don’t understand this behavior, and it doesn’t seem to happen with lists or basic variables. Example code:
class TestClass:
def __init__(
self,
adir={},
alist=[],
avar=None
):
print("input adir: " + str(adir)) #for test2, shows test1.mydir
self.mydir = adir
self.mylist = alist
self.myvar = avar
test1 = TestClass()
test1.mydir['a'] = 'A'
test1.mylist = ['foo']
test1.myvar = 5
test2 = TestClass()
print(test2.mydir) #has same value of test1!
print(test2.mylist)
print(test2.myvar)
The output looks like this:
initializing test1
input adir: {}
initializing test2
input adir: {‘a’: ‘A’}
{‘a’: ‘A’}
[]
None
Why does the dictionary argument (adir) to test2 get set to test1.mydir? Especially, why is the behaviour different than other mutable types like list?
Thank you!
As DSM says, don’t modify mutable default arguments. Do this instead: