Lifetime of a local reference

Marko Rauhamaa marko at pacujo.net
Thu Feb 28 17:25:01 EST 2019


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.

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.

> 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.


Marko



More information about the Python-list mailing list