Watch Out for Default Parameters in Python

As a C# developer that is new to Python, I equate the notion of default parameters in a function with being able to overload methods in a C# class. Now, I know that this is not a clean comparison, but in one since the goal of both devices are the same: provide for flexibility in how a method is called.

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?

Tags: python, programming, software