Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
gh-137288: Fix bug where boolean expressions are not associated with …
…the correct exception handler
  • Loading branch information
iritkatriel committed Aug 1, 2025
commit 71b151d29388448c027c286246a50678a4852283
15 changes: 15 additions & 0 deletions Lib/test/test_compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -1723,6 +1723,21 @@ def test_compound(self):
self.assertIs(res, v[3])
self.assertEqual([e.called for e in v], [1, 1, 0, 1, 0])

def test_exception(self):
# See gh-137288
class Foo:
def __bool__(self):
raise NotImplementedError()

a = Foo()
b = Foo()

with self.assertRaises(NotImplementedError):
bool(a)

with self.assertRaises(NotImplementedError):
c = a or b

@requires_debug_ranges()
class TestSourcePositions(unittest.TestCase):
# Ensure that compiled code snippets have correct line and column numbers
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix bug where some bytecode instructions of a boolean expression are not
associated with the correct exception handler.
6 changes: 6 additions & 0 deletions Python/flowgraph.c
Original file line number Diff line number Diff line change
Expand Up @@ -3477,13 +3477,15 @@ convert_pseudo_conditional_jumps(cfg_builder *g)
.i_oparg = 1,
.i_loc = loc,
.i_target = NULL,
.i_except = instr->i_except,
};
RETURN_IF_ERROR(basicblock_insert_instruction(b, i++, &copy));
cfg_instr to_bool = {
.i_opcode = TO_BOOL,
.i_oparg = 0,
.i_loc = loc,
.i_target = NULL,
.i_except = instr->i_except,
};
RETURN_IF_ERROR(basicblock_insert_instruction(b, i++, &to_bool));
}
Expand Down Expand Up @@ -3726,13 +3728,15 @@ insert_prefix_instructions(_PyCompile_CodeUnitMetadata *umd, basicblock *entrybl
.i_oparg = 0,
.i_loc = loc,
.i_target = NULL,
.i_except = NULL,
};
RETURN_IF_ERROR(basicblock_insert_instruction(entryblock, 0, &make_gen));
cfg_instr pop_top = {
.i_opcode = POP_TOP,
.i_oparg = 0,
.i_loc = loc,
.i_target = NULL,
.i_except = NULL,
};
RETURN_IF_ERROR(basicblock_insert_instruction(entryblock, 1, &pop_top));
}
Expand Down Expand Up @@ -3763,6 +3767,7 @@ insert_prefix_instructions(_PyCompile_CodeUnitMetadata *umd, basicblock *entrybl
.i_oparg = oldindex,
.i_loc = NO_LOCATION,
.i_target = NULL,
.i_except = NULL,
};
if (basicblock_insert_instruction(entryblock, ncellsused, &make_cell) < 0) {
PyMem_RawFree(sorted);
Expand All @@ -3779,6 +3784,7 @@ insert_prefix_instructions(_PyCompile_CodeUnitMetadata *umd, basicblock *entrybl
.i_oparg = nfreevars,
.i_loc = NO_LOCATION,
.i_target = NULL,
.i_except = NULL,
};
RETURN_IF_ERROR(basicblock_insert_instruction(entryblock, 0, &copy_frees));
}
Expand Down
Loading