Once-only evaluation of default parameter values functiondefinitions

Terry Reedy tjreedy at udel.edu
Tue Apr 13 02:10:16 EDT 2004


"Fred Ma" <fma at doe.carleton.ca> wrote in message
news:407B79D7.424F65A1 at doe.carleton.ca...
> Hello,
>    Example#1
>    ---------
>    def f(a, L=[]):
>        L.append(a)
>        return L
>
> Instead, one should use:
>
>    Example#2
>    ---------
>    def f(a, L=None):
>        if L is None:
>            L = []
>        L.append(a)
>        return L
>
>    print f(1)
>    print f(2)
>    print f(3)
>
> prints
>
>    [1]
>    [1, 2]
>    [1, 2, 3]
>=
> The alternative explanation that I could think of is that L is bound
> to the unnamed object [], and the object itself changes values to
> reflect changes to L i.e. L is now a persistent variable, retaining
> its value between function calls unless a value is provided for L in
> the function call's argument list.

More or less correct except that it is the object that you should think of
as persistent.  The variable L only exists during the function call.

  In the latter case, one can
> imagine L simply being overwritten with the value provided.

When one is provided.

> The problem with this picture is that Example#2 should fail for the
> same reasons as Example#1.  That is, L will not get the value of None
> on the 2nd call to f() without a value specified for L.

L gets bound to None whenever not overriden, on a per call basis.

> Hence, L will  not be reset to [].

Hence L *will* be reset to []







More information about the Python-list mailing list