Something in the function tutorial confused me.

Neil Cerutti horpner at yahoo.com
Mon Aug 6 14:04:12 EDT 2007


On 2007-08-06, Lee Fleming <countblabula at yahoo.com> wrote:
> On Aug 6, 12:30 pm, "Hamilton, William " <wham... at entergy.com> wrote:
>> When you call f(23), the variable y within it gets created and points at
>> None.  When f(23) exits, the y that it created gets destroyed.  (Well,
>> goes out of scope, but even if it's not garbage collected it won't ever
>> come back into scope.)  When you then call f(24), a new y is created
>> that also points to None, and disappears forever when f(24) exits.
>>
>> The values in a def statement are created when the def is executed, but
>> the variables are only created when the function is actually called, and
>> new ones are created every time the function is called.
>>
>> --
>> -Bill Hamilton- Hide quoted text -
>>
>> - Show quoted text -
>
> why isn't the y in def f (x, y = []): something
> garbage-collected?

Because the result of evaluating [] is stored somewhere in f as a
default argument. The result of evaluating [] is a new empty
list. It will never be garbage collected, because f maintains a
reference to it. Note that while [] and None may appear to be
similar expressions, they are not. None evaluated to itself,
while [] evaluates to a new empty list.

>>> None is None
True
>>> [] is []
False

-- 
Neil Cerutti
8 new choir robes are currently needed, due to the addition of several new
members and to the deterioration of some of the older ones. --Church Bulletin
Blooper



More information about the Python-list mailing list