Something in the function tutorial confused me.

Ricardo Aráoz ricaraoz at gmail.com
Tue Aug 7 08:15:38 EDT 2007


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).

(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.
(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.

(ii) (b) if y keeps the value it has when last exiting the function that
would explain that the second time you call it the list returned will
have two members.
(ii) (a) But then if it is "def f(x, Y = None)" when the "if" is
evaluated the empty list is assigned to y. So y will NO LONGER be None.
The second time the function is called y is NOT None (remember it keeps
it's last value) and the function returns a list with two members.

So, as I see it, the behavior is not coherent, the function treats y
differently according to the value it has assigned.

Please correct me!







More information about the Python-list mailing list