Lifetime of a local reference

Thomas Jollans tjol at tjol.eu
Wed Feb 27 04:30:06 EST 2019


On 27/02/2019 04.14, Alan Bawden wrote:
> Marko Rauhamaa <marko at pacujo.net> writes:
>> I couldn't find an immediate answer in the documentation.
> 
> I suspect that given the history of Python, pretty much everybody has
> always assumed that a Python implementation will not delete local variables
> early.  But I agree with you that the Python Language Reference does not
> appear to address this question anywhere!
> 

That's probably right. However, due to the nature of Python, things like
this are possible:

>>> v = 'a'
>>> def f():
...     a, b, c = 1, 2, 3
...     return eval(v)
...
>>> f()
1
>>> v = 'b'
>>> f()
2
>>>


What I mean to say is that it's not in general trivial (or even
possible) to tell if a local is referred to later in the function body.
I think we can say that a Python interpreter can't delete a local before
having executed any statement that could *possibly* access it.

If the inspect module's stack frame inspection machinery is supported,
then any function call might access any local... (though I don't think a
compliant Python implementation necessarily has to support the inspect
module fully). And we're back to where we started.

-- Thomas



More information about the Python-list mailing list