[Tutor] Python function seem to have a memory ???

Simon Vandemoortele delirious@atchoo.be
Sat, 11 Aug 2001 14:42:50 -0100


I am making my first contact with python through the means of the tutoria=
l
(http://www.python.org/doc/current/tut/) and I would like some clarificat=
ion=20
on the example:

--- quote ---
Important warning: The default value is evaluated only once. This makes a=
=20
difference when the default is a mutable object such as a list or diction=
ary.=20
For example, the following function accumulates the arguments passed to i=
t on=20
subsequent calls:=20

def f(a, l =3D []):
    l.append(a)
    return l
print f(1)
print f(2)
print f(3)

This will print=20

[1]
[1, 2]
[1, 2, 3]
--- end quote ---

One thing I find astonishing about this is the fact that python functions=
=20
seem to have memory; each call of f() leads to a different result ! Does =
this=20
mean that the variable 'l' keeps its content even after the function retu=
rns=20
? This seems very strange to me as I have never seen it in other language=
s.=20

Some explanation/comments/corrections ?
Thx, Simon

--=20
If you took all the students that felt asleep in class and laid them
end to end, they'd be a lot more comfortable.
=09=09-- "Graffiti in the Big Ten"