0

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'}
Community
  • 1
  • 1
Niek de Klein
  • 8,524
  • 20
  • 72
  • 143
  • See the "important warning" in the [Python Tutorial](http://docs.python.org/tutorial/controlflow.html#default-argument-values). We get this question at least once a week... – Sven Marnach Mar 22 '12 at 14:53
  • Sorry that I didn't find it, I didn't search for 'Least Astonishment in python' or 'The mutable default argument' – Niek de Klein Mar 22 '12 at 14:56
  • There are hundreds of questions along these lines on SO. The fact that this comes up so often indicates that it seems to be indeed difficult to find, but I don't know how to improve the situation. – Sven Marnach Mar 22 '12 at 15:02
  • Problem is that this phenomenon isn't easy to search for the first time you come across it. I think it's a bit harsh marking this question down and closing it (4 close votes at time of writing). – MattH Mar 22 '12 at 15:02
  • @MattH: I think closing it is fine, since it is a duplicate. And I didn't mean to "make it down". – Sven Marnach Mar 22 '12 at 15:03
  • Perhaps it's so hard to find because title variations are closed as duplicates. – MattH Mar 22 '12 at 15:05
  • @MattH: Closing a question doesn't mean it is deleted, so this can't be the reason. – Sven Marnach Mar 22 '12 at 15:11

2 Answers2

1

Function arguments in python are only initialized once. If you want it to be per-call, just initialize it as an empty dict inside your function.

Tyler Eaves
  • 12,879
  • 1
  • 32
  • 39
1

Because here dct={} makes default value of dct always 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.

ZelluX
  • 69,107
  • 19
  • 71
  • 104