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

Mark Shannon report at bugs.python.org
Mon Feb 1 19:03:23 EST 2021


Mark Shannon <mark at hotpy.org> added the comment:

The differences between allowing the optimiser to remove truly redundant (in terms of control flow) boolean tests, or not, is slight.
It only matters for __bool__() calls that have side effects. Like __hash__(), __bool__() should not produce side effects.


There are three options, each with their own issues.

1. Freely remove redundant boolean checks, which means that

b = B()
try:
    if b: pass
except:
    print("This won't happen, but it used to")

will not print anything.

2. Don't remove redundant boolean checks, which prevents optimizations to remove repeated checks in short-circuiting operators, and would be a regression in terms of efficiency.

3. Attempt some sort of complex compromise. This is hard to get right, especially once the optimizer has started to transform the code.
It is also likely to produce inconsistencies, in that `True or b` might behave differently from `b or True`. Both are true, but one might raise an exception, whereas the other might not.


I favour option 1. It is already implemented. It is consistent both with itself, and with optimizations up to 3.9.
PEP 626 means that it will generally only be applied to short-circuiting operators and will not eliminate entire lines.


Note:

b = B()
try:
    if b: 
         pass
except:
    print("This will still happen")

Will print, as PEP 626 requires the execution of the pass statement to be observable, as it is on a line by itself. Consequently the test must be performed.

Given that this is quite obscure, I don't think it is a problem to release an alpha with this unresolved.
I would like to resolve it before beta.

----------

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


More information about the Python-bugs-list mailing list