Lifetime of a local reference
roel at roelschroeven.net
Wed Feb 27 16:39:05 EST 2019
Rhodri James schreef op 27/02/2019 om 15:18:
> On 27/02/2019 06:56, Marko Rauhamaa wrote:
>> Alan Bawden <alan at csail.mit.edu>:
>>> But I appreciate that that isn't the true question that you wanted to ask!
>>> You are wondering if a Python implementation is _permitted_ to treat the
>>> code you wrote _as if_ you had written:
>>> def fun():
>>> f = open("lock")
>>> flock.flock(f, fcntl.LOCK_EX)
>>> del f
>>> which deletes the variable f from the local environment at a point where it
>>> will never be used again. (Which could cause the lock to be released
>>> before do_stuff is even called.)
>>> This is an interesting question, and one that any garbage collected
>>> language should probably address somehow.
> Interesting indeed. My gut instinct was "Hell, no!", but as Marko
> points out C optimisers do exactly that, and I don't find it
> particularly surprising in practice. I don't think that there is
> anything in the docs that says a compliant implementation couldn't
> delete variables early. The nearest you get is repeated reminders that
> you can't make assumptions about when destructors will be run.
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
"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).
"Honest criticism is hard to take, particularly from a relative, a
friend, an acquaintance, or a stranger."
-- Franklin P. Jones
More information about the Python-list