[Tutor] Python function seem to have a memory ???
Sun, 12 Aug 2001 22:17:47 +0100
> --- quote ---
> Important warning: The default value is evaluated only once.
This is the key statement
> def f(a, l = ):
> return l
So the default is a reference to an empty list
> print f(1)
and now we put a=1 into that list
> print f(2)
and now a=2 goes in. its the same list because python
only evaluates the default once when the function is defined.
This is rather like "closure" behaviour in other languages
like perl or lisp. Indeed you can use this behaviour to make
lambda functions more useful(you'll cover lambdas later ;-)
> One thing I find astonishing about this is the fact that
> python functions seem to have memory;
Correct, it remembers the default and, as it is mutable,
the content changes. This can be useful when you want it
and infuriating when you don't!