Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
I was working on a dictionary when I noticed that if you have an empty dict as input of the function, after giving it input in the function the next time the function is called the dict isn’t empty anymore. I have trouble explaining what I mean, so I hope the following piece of code explains what I mean:
>>> def test(input, dct={}):
... dct[input] = 'test'
... print dct
...
>>> test('a')
{'a': 'test'}
>>> test('b')
{'a': 'test', 'b': 'test'}
My question boils down to: why in this example script, when doing test(‘b’), does it print
{'a':'test', 'b':'test'}
instead of
{'b':test'}
Because here
dct={}makes default value ofdctalways pointing to the same object, instead of creating an empty dictionary every time. This is a common pitfall Python programmers may fall into.This article explains this problem in detail.