Function attributes: a bug?

Erik Max Francis max at alcyone.com
Sat Mar 29 11:33:43 EST 2003


Tj wrote:

> But there's a bug -- if I generate a function using this, use it for a
> while to build up a list, then call make_list_accum() again, it will
> want to init itself with the other list by default, sharing it!  This
> is surprising behavior, and doesn't happen if I don't use this
> optional init form.

This doesn't have anything to do with functio attributes; what you're
discovering is that default arguments are only evaluated once:

>>> def f(x, l=[]):
...  l.append(x)
...  print l
... 
>>> f(1)
[1]
>>> f(2)
[1, 2]
>>> f(3)
[1, 2, 3]

When the default argument is mutable, and you want to make sure you
don't run into this issue, use an immutable sentinel in the argument and
test for it in the body:

>>> def g(x, l=None): 
...  if l is None:
...   l = []
...  l.append(x) 
...  print l
... 
>>> g(1)
[1]
>>> g(2)
[2]
>>> g(3)
[3]

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Divorces are made in Heaven.
\__/ Oscar Wilde
    Bosskey.net: Counter-Strike / http://www.bosskey.net/cs/
 A personal guide to Counter-Strike.




More information about the Python-list mailing list