I was reading this today: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#default-parameter-values and I can’t seem to understand what’s happening under the hood.
def bad_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
The problem here is that the default
value of a_list, an empty list, is
evaluated at function definition time.
So every time you call the function,
you get the same default value. Try it
several times:
I guess first of all, when is the function definition stage? Is it an initialization stage just before the actual main function executes?
My original thinking was that the name a_list gets discarded right after the function runs so whatever [] mutated to will be garbage collected. Now, I think that a_list is not discarded at all since it’s only a name bound to the object [] so it never gets garbage collected because a_list is still bound to it. But then again, I’m wondering how I still get the same default value instead of a new []. Can someone straighten this out for me?
Thanks!
Look at "Function definitions" in the Python reference:
The parameters are evaluated when the function definition is executed. If this is in a module, it happens when the module is imported. If it’s in a class, it’s when the class definition runs. If it’s in a function, it happens when the function executes. Remember that a Python module is evaluated from top to bottom, and doesn’t automatically have an explicit "main function" like some languages.
For example, if you put the function definition inside a function, you get a new copy of the function each time:
The function definition creates a new
functionobject, assigns it various properties including the code, formal parameters, and default values, and stores it in a name in the scope. Typically this only happens once for any given function, but there are cases where a function’s definition can be executed again.Inside the body of the function, the name
a_listis available to the code. So the name, and the value it is pointing to, must both still be available. It is stored in thefunc_defaultsattribute of the function.Because the
[]is evaluated only when the function is defined, not when it is called, and the namea_listpoints to the same object even across repeated calls. Again, if you want the alternative behavior, use something immutable likeNoneand check for it.