Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
As I was reading the following handout: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables
I came across the following example. Basically, it claims that:
def bad_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
is not the best way to append items to a list since a_list
is evaluated at at function definition time.
Instead, a better alternative is:
def good_append(new_item, a_list=None):
if a_list is None:
a_list = []
a_list.append(new_item)
return a_list
since it defines the variable in the function's runtime.
Coming from a C-background, isn't a_list
a local variable here? How does it store its value from one function call to the other? Furthermore, can someone please elaborate on why the second example is better than the first? What's wrong with defining functions in the definition? It doesn't seem like it overwrites the original value or anything.
Thanks!