Once-only evaluation of default parameter values function definitions
Fred Ma
fma at doe.carleton.ca
Tue Apr 13 05:55:10 EDT 2004
Michael Geary wrote:
> > Example#1
> > ---------
> > def f(a, L=[]):
> > L.append(a)
> > return L
> >
> > Example#2
> > ---------
> > def f(a, L=None):
> > if L is None:
> > L = []
> > L.append(a)
> > return L
>
> Here's a simpler example:
>
> >>> a = []
> >>> b = a
> >>> a
> []
> >>> b
> []
> >>> a.append(1)
> >>> a
> [1]
> >>> b
> [1]
>
> See what happened? The statement 'b = a' didn't make a copy of a and
> store it in b. Instead, it made the name b refer to the same object
> as a. So, when I said b.append(1), it meant exactly the same thing
> as if I'd said a.append(1).
Thanks, Mike. That's alot clearer. The default value looks like it's
a persistent object. It is similar to a static local variable in C++.
In Example#1, that object actually got changed. In contrast, in
Example#2, the code prevents L from remaining bound to None beyond the
first line, so the None object never gets changed. In fact, my 2nd
explanation was close: that there is an unnamed persistent object that
holds the default value to be bound to L for invocations that don't
explicity supply an argument for L. The place I went wrong was to say
that L never gets bound to None again, after it has been bound to a
caller supplied object on a previous invocation of the function.
Fred
More information about the Python-list
mailing list