[Tutor] Python function seem to have a memory ???
Lloyd Kvam
lkvam@venix.com
Sat, 11 Aug 2001 10:05:23 -0400
The function definition needs to store the default value. In the common case that will be a reference to an immutable constant such as None or 2.
This example sets the default to a container (a list). That container is not garbage collected so long as the function exists since the function's default is a reference to the container. Thus changes to the container will persist.
The final wrinkle is to have the function modify the container - it changes its default value each time it is run. This seems very sneaky, yet delightfully useful at times.
Simon Vandemoortele wrote:
>
> I am making my first contact with python through the means of the tutorial
> (http://www.python.org/doc/current/tut/) and I would like some clarification
> on the example:
>
> --- quote ---
> Important warning: The default value is evaluated only once. This makes a
> difference when the default is a mutable object such as a list or dictionary.
> For example, the following function accumulates the arguments passed to it on
> subsequent calls:
>
> def f(a, l = []):
> l.append(a)
> return l
> print f(1)
> print f(2)
> print f(3)
>
> This will print
>
> [1]
> [1, 2]
> [1, 2, 3]
> --- end quote ---
>
> One thing I find astonishing about this is the fact that python functions
> seem to have memory; each call of f() leads to a different result ! Does this
> mean that the variable 'l' keeps its content even after the function returns
> ? This seems very strange to me as I have never seen it in other languages.
>
> Some explanation/comments/corrections ?
> Thx, Simon
>
> --
> If you took all the students that felt asleep in class and laid them
> end to end, they'd be a lot more comfortable.
> -- "Graffiti in the Big Ten"
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice: 603-443-6155
fax: 801-459-9582