Something in the function tutorial confused me.
Hamilton, William
whamil1 at entergy.com
Mon Aug 6 14:14:50 EDT 2007
> From: Lee Fleming
> 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?
>
The y is garbage-collected. However, the [] in the def statement is
not. The list is created when the statement is evaluated. Every time
that f() is called with a default value, the new y created will point to
the same list. If that list is mutated into [23], it will still be [23]
the next time f() is called, and the new y created in that call will
point at the same list (now [23]) that the (now destroyed) y pointed to
in the first call.
--
-Bill Hamilton
More information about the Python-list
mailing list