Mutable default values for function parameters
Erik Max Francis
max at alcyone.com
Thu Oct 4 19:46:44 CEST 2001
> I'd like to point something that is said in §4.7.1 of the tutorial:
> "Important warning: The default value is evaluated only once. This
> makes a difference when the default is a mutable object such as a list
> or dictionary"
> I think that this point is really difficult to understand. That means
> that parameters with mutable default value are global to all the calls
> of the function:
> This is a really confusing and I always fall in this sort of trap.
> Maybe a bad neuronal connection;-)
I avoid this problem by simply never using a mutable object as a default
argument, but instead always using a sentinel value that's substituted
in the function body:
def sample(x, d = None):
if d is None:
d = 
To be honest, I can't remember ever running into this pitfall, since
I've used this pattern ever since I started using Python, and happened
to be made aware of the rule before encountering the wrong end of it.
Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
__ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/ \ Sanity is a cozy lie.
\__/ Susan Sontag
Alcyone Systems' CatCam / http://www.catcam.com/
What do your pets do all day while you're at work? Find out.
More information about the Python-list