Something in the function tutorial confused me.

David Wahler dwahler at gmail.com
Tue Aug 7 21:35:54 EDT 2007


On 8/7/07, Ricardo Aráoz <ricaraoz at gmail.com> wrote:
> Lee Fleming wrote:
> > Thanks for all the help, everyone. I guess I was confused with default
> > arguments that were mutable and immutable. I will continue to look
> > over these posts until I understand what is happening.
> >
> > I cannot believe the number of helpful responses I got!
> >
>
> Apparently he didn't understand.
> Neither did I.
>
> Either (i)y's initial value (None or []) is saved somewhere to be
> retrieved every time the function is called without 2nd argument, or
> (ii) y keeps the value it has when last exiting the function (if there
> is a third option, please mention it).
>

It's option (i).

> (i) (a) whenever the function is called without 2nd argument the value
> None is retrieved and assigned to y, thus causing [] to be assigned to y
> by the 'if' statement.

Yep.

> (i) (b) But then if it is "def f(x, y = [])" the list [] should be ALSO
> saved somewhere and when the function is called without 2nd argument it
> should be retrieved and assigned to y, thus y would always be [] when
> you enter the function without 2nd arg.

No, when the def statement is executed, the expression [] is
evaluated, and the result of this evaluation is an empty list. It's a
reference to this list that is saved, not the expression itself. All
invocations of the function that use the default argument refer to the
same list, so if it gets modified the modifications persist.

-- David


More information about the Python-list mailing list