[Tutor] Python function seem to have a memory ???
Sun, 12 Aug 2001 18:36:09 -0400
Others have already explained why it works the way it does, but
haven't given an example of how to get a default argument value of a
new empty list each time the function is called.
On Sat, Aug 11, 2001 at 02:42:50PM -0100, Simon Vandemoortele wrote:
| --- 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 = ):
| return l
| print f(1)
| print f(2)
| print f(3)
| This will print
| [1, 2]
| [1, 2, 3]
| --- end quote ---
def f( a , l = None ) ;
if l is None :
l = 
l.append( a )
'None' is an immutable object. This means it can't change and will
always be the same. The first thing I do in the function is to see if
'l' has the default value. If it does I create a new local binding to
a new empty list object called 'l'. Then I proceed to modify it and
return it as before. This idiom will have the desired effect.