def X(l=[]): weirdness. Python bug ?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Fri Aug 22 06:04:20 EDT 2008


Bart van Deenen a écrit :
(ot : please don't top post - corrected)
> cokofreedom at gmail.com wrote:
> 
>> On Aug 22, 11:13 am, Bart van Deenen 
>> <b... at at.vandeenensupport.punt.com.invalid> wrote:
>>> # function def X(l=[]): l.append(1) print l
>>> 
>>> # first call of X X() [1]
>>> 
>>> #second call of X X() [1, 1]
>>> 
>>> Where does the list parameter 'l' live between the two successive
>>> calls of X(). Why is it not recreated with an empty list? Is this
>>> correct behavior or is it a Python bug? Does anyone have any
>>> pointers to the language documentation where this behavior is
>>> described?
>>> 
> 
>> "Default parameter values are evaluated when the function
>> definition is executed."
>> 
(snip)
 > Thanks all for your answers. I figured your solution already, but now
 > I understand where the behavior is from. One question remains: can I
 > find my parameter 'l' somewhere? I looked in a lot of objects, but
 > couldn't find it.

def foo(x="default value for x"):
     pass

print foo.func_defaults
=> ('default value for x',)





More information about the Python-list mailing list