Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 05f8318

Browse files
authored
bpo-37269: Correctly optimise conditionals with constant booleans (GH-14071)
Fix a regression introduced by af8646c that was causing code of the form: if True and False: do_something() to be optimized incorrectly, eliminating the block.
1 parent d0eeb93 commit 05f8318

3 files changed

Lines changed: 14 additions & 0 deletions

File tree

Lib/test/test_peepholer.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,13 @@ def forloop():
414414
pass
415415
self.assertEqual(count_instr_recursively(forloop, 'BUILD_LIST'), 0)
416416

417+
def test_condition_with_binop_with_bools(self):
418+
def f():
419+
if True or False:
420+
return 1
421+
return 0
422+
self.assertEqual(f(), 1)
423+
417424

418425
class TestBuglets(unittest.TestCase):
419426

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a bug in the peephole optimizer that was not treating correctly constant
2+
conditions with binary operators. Patch by Pablo Galindo.

Python/peephole.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,11 @@ PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names,
315315
fill_nops(codestr, op_start, nexti + 1);
316316
cumlc = 0;
317317
} else if (is_true == 0) {
318+
if (i > 1 &&
319+
(_Py_OPCODE(codestr[i - 1]) == POP_JUMP_IF_TRUE ||
320+
_Py_OPCODE(codestr[i - 1]) == POP_JUMP_IF_FALSE)) {
321+
break;
322+
}
318323
h = get_arg(codestr, nexti) / sizeof(_Py_CODEUNIT);
319324
tgt = find_op(codestr, codelen, h);
320325
fill_nops(codestr, op_start, tgt);

0 commit comments

Comments
 (0)