Python bug with [] as default value in functions?

Dinu Gherman dinu at reportlab.com
Thu Apr 12 10:54:11 EDT 2001


On Thu, 12 Apr 2001 13:55:04 +0100, Robin Becker
<robin at jessikat.fsnet.co.uk> wrote:

>Hi I think you are getting involved with one of the standard 'features'
>of python.
>
>eg
>>>> def dingo(n,L=[]):
>...     if n: L.append(n)
>...     return L
>... 
>>>> dingo(1)
>[1]
>>>> dingo(0)
>[1]
>>>>
>
>ie the first call of dingo modified the default argument. Since the
>empty list is mutable that particular version of it gets modified by the
>first call and changes the default for the second.
>
>Hope your tooth ache is better. 


I guess your example shouldn't use 0 (although the result does not 
change, in this case). So you still get this:

>>> def pingo(n, L=[]):
... 	if n: L.append(n)
... 	return L
... 
>>> 
>>> pingo(1)
[1]
>>> pingo(0)
[1]
>>> pingo(2)
[1, 2]
>>> 

Instead, I claim one should get the following: 

>>> pingo(1)
[1]
>>> pingo(0)
[]
>>> pingo(2)
[2]
>>> 

I can work around that 'feature', but I'm pretty sure I don't like it!
It makes a very good candidate for a "Python Obscurities" collection!

This is entirely different from a recursive context, where I *do*
expect the list to be shared across different calls on different lev-
els! And effectively it is, but only when I provide the default value
in the top-level call (adding to the *obscurity* list as well ;-).

Not-much-enlighted'ly,

Dinu


-- 
Dinu C. Gherman
dinu at reportlab dot com
http://www.reportlab.com
................................................................
"The only possible values [for quality] are 'excellent' and 'in-
sanely excellent', depending on whether lives are at stake or 
not. Otherwise you don't enjoy your work, you don't work well, 
and the project goes down the drain." 
                    (Kent Beck, "Extreme Programming Explained")



More information about the Python-list mailing list