static variables?

Erik Max Francis max at alcyone.com
Tue Nov 19 21:59:35 EST 2002


Mike Dean wrote:

> I've seen this trick a time or two before and always wondered - why
> does
> it work?  Why does Python remember the changed list as the function's
> default value, rather than reverting back to the list that was
> specified when the function was defined?  At first glance it seems a
> bit non-intuitive.

Because when you define a default value for a function parameter, the
value is always the same object; it's not reinitialized each time.  This
doesn't really matter when the object is immutable (since it can't
change it doesn't matter that it's always the same object), but when
it's mutable you need to be careful.

If you really do want a different each object each time, then do
something like:

	def f(x, l=None):
	    if l is None:
	        l = [] # now it's a new list each time
	    ...

As for the "why," I think it's just a historical accident which is too
late to change now.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Nationalism is an infantile sickness.
\__/ Albert Einstein
    Blackgirl International / http://www.blackgirl.org/
 The Internet resource for black women.



More information about the Python-list mailing list