Bart van Deenen wrote:
Hi all.
I've stumbled onto a python behavior that I don't understand at all.
Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
# 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?
Thanks all
Bart van Deenen
I happen to be reading about decorators at the moment:
from copy import deepcopy
def nodefault(myfunc):
myfunc_defaults = myfunc.func_defaults
def fresh(*args, **kwargs):
myfunc.func_defaults = deepcopy(myfunc_defaults)
return myfunc(*args, **kwargs)
return fresh
@nodefault
def X(l=[]):
l.append(1)
print l
>>> for i in range(1,6):
... X()
...
[1]
[1]
[1]
[1]
[1]
Which is just a very fancy way of doing:
def X(l=[]):
if l is None:
l = []
l.append(1)
print l
* sound of two pennies *
--
http://mail.python.org/mailman/listinfo/python-list