[issue42899] Is it legal to eliminate tests of a value, when that test has no effect on control flow?

Guido van Rossum report at bugs.python.org
Tue Jan 12 10:47:39 EST 2021


Guido van Rossum <guido at python.org> added the comment:

Can we translate 'if x: pass' into 'pass'? No, because calling its __bool__ method may have a side effect (as we saw at the start of this thread).

Can we eliminate a lone 'x'? Only if it's a local variable and we're *sure* (because of control flow analysis) that it's got a value. For globals and class variables we must execute the load because there could always be an exception (or the dict could have a trap for lookups).

Can we eliminate e.g. 'x.y'? Never, because it can have a side effect.

In general, eliminating this kind of thing seems silly -- in code that the user intends to be fast such things don't occur, and in test the user probably has a reason to write odd code.


On the other question, I don't see how there's any possible difference in evaluation and side effects between

if a and b: ...

and

if a:
    if b:
        ...

so I have no problem with that (in fact that is what it *means*).

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue42899>
_______________________________________


More information about the Python-bugs-list mailing list