On Sun, Oct 10, 2021 at 09:15:30AM +0000, Patrick Reader wrote:

> - a LOAD_FAST cannot possibly have any side-effects outside the 
> interpreter stack [1]

> [1]: global variables are probably supposed to have the same 
> guarantee, but in practice this is not the case

I don't think that lookups are guaranteed to be side-effect free, since 
raising an exception is a side-effect.

    def func():
        x

can raise NameError if there is no global or builtin "x". So that cannot 
be optimized away. Similarly for locals:

    def func(x):
        if random.random() > 0.5:
            del x
        x

Will that raise or not? No way of telling without actually running the 
code.

Now I guess a sufficiently smart optimizer might be able to optimize 
away the lookup of a local variable if it cannot possibly be undefined, 
as in your initial example, but that brings us to how much benefit is 
gained for how much developer effort and code complexity.

If the benefit is small, or negligible, then the developer effort 
had better be even smaller.

In this case, the cost of the lookup is small (it is a *FAST* lookup). 
And furthermore, the likelihood that anyone will actually write that 
code is even smaller.

(There are times that we might test for the existence of a global, by 
looking up the name. There might even be times that we would do the same 
for a local. We might even, under some rare circumstances, do so without 
guarding it in a try...except block. But why on earth would we test for 
the existence of a local that cannot possibly fail to exist, which is 
the only case that is safe to optimize away?)

So the benefit is correspondingly tiny, and optimizing it away had 
better be effectively free in both developer effort and ongoing code 
complexity to make it worthwhile.


-- 
Steve
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/python-dev@python.org/message/HWSHZLW64Q26EIUPX4S3TME5QXYBRLPY/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to