Default Value

Lefavor, Matthew (GSFC-582.0)[MICROTEL LLC] matthew.lefavor at nasa.gov
Thu Jun 20 18:28:06 EDT 2013


Or, in many MANY cases, the choice was the right one, but isn't
obvious to everyone.

I think it's worth pointing out that changing function defaults to
late-binding would merely change the nature of the gotcha, not eliminate it.

words = ("one", "two", "red", "blue", "fish")

def join_strings(strings=words):
   return ' '.join('%s %s' % (s, strings[-1]) for s in strings[:-1])

# Later:
words = open("gettysburg_address.txt", "r").read().split()
# Oops, the default argument of join_strings just changed.

+1. This is what convinces me that keeping references to keyword arguments is actually the right thing to do.

Perhaps I'm biased because I'm used to the mutable-argument behavior by now, but the gotcha described above seems to be much harder to track down and understand than any bugs caused by mutable arguments. With mutable arguments, at least you know the cause is in the function definition. If you initialized variables each time, you'd have to track the problem down across the entire namespace.

I, for one, would much rather follow the rule "don't use mutable arguments in function definitions" than "don't ever re-use the name of your variables."

ML
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130620/0fdb438c/attachment.html>


More information about the Python-list mailing list