Lifetime of a local reference

Chris Angelico rosuav at gmail.com
Thu Feb 28 18:01:02 EST 2019


On Fri, Mar 1, 2019 at 9:31 AM Marko Rauhamaa <marko at pacujo.net> wrote:
>
> Roel Schroeven <roel at roelschroeven.net>:
> > In the absence of any other mention of bindings being removed, to me
> > it seems clear that bindings are not automatically removed. Otherwise
> > many things become ambiguous. Example: the documentation for dicts
> > defines "d[key] = value" as "Set d[key] to value". Does that mean it
> > can get unset later behind your back? Of course not.
>
> Nothing is so obvious here.
>
> A Python implementation is free to do anything at all that complies with
> correct semantics. Sometimes correct behavior is unspecified.
>
> In your case, "d[key] = value", the binding can disappear if the name d
> becomes "stale". d[key] will be bound if anybody should look but if the
> compiler or runtime environment can prove nobody will every look, it
> might be able to optimize it away.

The point was that so long as d exists, so does d[key]. There is no
way for d[key] to legitimately become "stale" and expired. There is
also no way for a function local name to become "stale" while it's
running. They are attributes of the function's context.

> If you accept that
>
>    open("xyz")
>
> can silently close the file immediately, sometime later or never, you
> should have no problem believing that
>
>    f = open("xyz")
>
> could behave the same way.

No, because 'f' is a name.

> > It's purely an implementation detail. As long as the visible behavior
> > of the program complies with the language specification, the compiler
> > can do as it wishes.
>
> And that's the key: what is specified for Python? It would appear
> nothing has been stated explicitly so it would be dangerous for a Python
> application to rely on assumed semantics.

Not true.

ChrisA


More information about the Python-list mailing list