Watch Out for Default Parameters in Python
June 18, 2007
Well, I ran into a nasty bug that took some time to resolve and even more time to fully understand why it had occurred.
It turns out that when a default parameter is used in a function, a global variable is created and assigned that default value once. Then, if that mutable parameter (e.g. dict) is modified within the function, subsequent calls to that function that make use of the default parameter, will retain that value from call to call. This can be avoided by not using default values in the parameter list, passing in values to the function that has default values, or defaulting to something like None and then checking for None in the function and assigning it the default value.
In Learning Python, the author claims that this is an intended feature of the language. However, from what I read I don't yet see how this behavior is something that would be desired in a language.
Can anyone help me see the light with regards to this issue?