Why the "mutable default argument fix" syntax is so ugly, asks python newbie
- by Cawas
Now following my series of "python newbie questions" and based on another question.
Go to http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#other-languages-have-variables and scroll down to "Default Parameter Values". There you can find the following:
def bad_append(new_item, a_list=[]):
a_list.append(new_item)
return a_list
def good_append(new_item, a_list=None):
if a_list is None:
a_list = []
a_list.append(new_item)
return a_list
So, question here is: why is the "good" syntax over a known issue ugly like that in a programming language that promotes "elegant syntax" and "easy-to-use"?
Why not just something in the definition itself, that the "argument" name is attached to a "localized" mutable object like:
def better_append(new_item, a_list=[].local):
a_list.append(new_item)
return a_list
I'm sure there would be a better way to do this syntax, but I'm also almost positive there's a good reason to why it hasn't been done. So, anyone happens to know why?