Mutable default values for function parameters
Erik Max Francis
max at alcyone.com
Thu Oct 4 15:04:48 EDT 2001
Steve Holden wrote:
> I've used this idiom myself many times. I eventuallu decided it was
> def sample(x, d = None):
> d = d or 
> print d
> but this looks so weird I'd appreciate confirmation that it's a valid
d would be replaced with a new empty list if it evaluated to false,
rather than only if it is the sentinel value (in this case, None).
There _is_ a difference there, since lots of things can evaluate to
false, not just None. Plenty of non-lists evaluate to false (zeroes,
empty strings, etc.). More importantly, though, empty sequence objects
evaluate to false. Even in this case, you can come up with a case that
would be unexpected. With your definition above, consider:
>>> l = [1, 2]
>>> sample(3, l)
[1, 2, 3]
[1, 2, 3]
>>> l = 
>>> sample('a', l)
l is an empty list so it evaluates to false, and so your hack replaced
it with a new, local list. That probably isn't what was intended.
I'm all for replacing wordy idioms with shorter, equivalent ones to save
typing and to increase clarity, but in this case it decreases clarity
and actually means something (subtly) different.
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ Magnificent desolation.
\__/ Buzz Aldrin (on the Moon)
Alcyone Systems / http://www.alcyone.com/
Alcyone Systems, San Jose, California.
More information about the Python-list