Something in the function tutorial confused me.

Steve Holden steve at holdenweb.com
Wed Aug 8 03:39:05 CEST 2007


Ricardo Aráoz 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).
> 
> (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!

OK. The difference is that [] is a mutable value, while None is 
immutable. So when the function starts out with [] as y's value, and the 
value gets changed, the same value is used the next time the function is 
called and the second call sees the mutated value.

When the function starts out with None as y's value any assignment to y 
causes it to reference a different value (since None is immutable). So 
the next time the function is called y is pointing at the None that it 
was pointing at the last time the function was called (since None cannot 
be mutated).

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------




More information about the Python-list mailing list