If you go to https://david.goodger.org/projects/pycon/2007/idiomatic/handout.html#default-parameter-values, 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
There's even an "Important warning" on python.org with this very same example, though not really saying it's "better".
Why is the "good" syntax over a known issue ugly like that in a programming language that promotes "elegant syntax" and "easy-to-use"? Or to put it another way, why is there no simpler alternative built into the language?
I think a better way would probably being able to do something in the def
itself, in which the name argument would be attached to a "local", or "new" within the def
, mutable object. Something like:
def better_append(new_item, a_list=immutable([])):
a_list.append(new_item)
return a_list
Why hasn't something like this been done?