Lifetime of a local reference

Chris Angelico rosuav at gmail.com
Thu Feb 28 07:21:36 EST 2019


On Thu, Feb 28, 2019 at 11:13 PM Rhodri James <rhodri at kynesim.co.uk> wrote:
>
> On 27/02/2019 21:39, Roel Schroeven wrote:
> > Rhodri James schreef op 27/02/2019 om 15:18:
> > Aren't we overthinking this?
> >
> > I think it's pretty clear that a variable is never deleted before it
> > goes out of scope. A quick search in the documentation points me to
> > (https://docs.python.org/3/reference/datamodel.html#objects-values-and-types):
> >
> >
> > "Objects are never explicitly destroyed; however, when they become
> > unreachable they may be garbage-collected. An implementation is allowed
> > to postpone garbage collection or omit it altogether — it is a matter of
> > implementation quality how garbage collection is implemented, *as long
> > as no objects are collected that are still reachable*." (emphasis mine)
> >
> > In the original example (without del), f is reachable everywhere in the
> > function after the initial binding, so it can not be deleted.
> >
> > Comparisons with C on this point don't seem very relevant: C doesn't
> > have destructors or garbage collection. I don't even see what the C
> > equivalent for "del f" could be. You could perhaps compare with C++,
> > where destructors are also not called before the object goes out of
> > scope (a difference is that in C++ the destructor explicitly always is
> > called at that moment).
>
> I think you're making the mistake of equating names ("variables") and
> objects here.  It is not clear to me that a name can't be removed from
> the dictionary of locals before it goes out of scope, so long as it
> doesn't get referred to again, just like C optimisers can note that a
> local doesn't get used again and reclaim the storage.  At that point the
> object can become unreachable, and will in Marko's example.
>
> The equivalent to "del f" that you can't imagine is the optimiser at work.
>

What if an exception gets raised at some point before the function has
returned? The exception object will give full access to the function's
locals.

ChrisA


More information about the Python-list mailing list