Skip to content

Commit 0e61d2b

Browse files
authored
[3.11] GH-95921: Fix positions for some chained comparisons (GH-96968) (GH-96973)
(cherry picked from commit dfc73b5) Automerge-Triggered-By: GH:brandtbucher
1 parent 32d80de commit 0e61d2b

File tree

3 files changed

+29
-0
lines changed

3 files changed

+29
-0
lines changed

Lib/test/test_compile.py

+26
Original file line numberDiff line numberDiff line change
@@ -1039,6 +1039,32 @@ def while_not_chained(a, b, c):
10391039
for instr in dis.Bytecode(while_not_chained):
10401040
self.assertNotEqual(instr.opname, "EXTENDED_ARG")
10411041

1042+
def test_compare_positions(self):
1043+
for opname, op in [
1044+
("COMPARE_OP", "<"),
1045+
("COMPARE_OP", "<="),
1046+
("COMPARE_OP", ">"),
1047+
("COMPARE_OP", ">="),
1048+
("CONTAINS_OP", "in"),
1049+
("CONTAINS_OP", "not in"),
1050+
("IS_OP", "is"),
1051+
("IS_OP", "is not"),
1052+
]:
1053+
expr = f'a {op} b {op} c'
1054+
expected_positions = 2 * [(2, 2, 0, len(expr))]
1055+
for source in [
1056+
f"\\\n{expr}", f'if \\\n{expr}: x', f"x if \\\n{expr} else y"
1057+
]:
1058+
code = compile(source, "<test>", "exec")
1059+
actual_positions = [
1060+
instruction.positions
1061+
for instruction in dis.get_instructions(code)
1062+
if instruction.opname == opname
1063+
]
1064+
with self.subTest(source):
1065+
self.assertEqual(actual_positions, expected_positions)
1066+
1067+
10421068
@requires_debug_ranges()
10431069
class TestSourcePositions(unittest.TestCase):
10441070
# Ensure that compiled code snippets have correct line and column numbers
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix overly-broad source position information for chained comparisons used as
2+
branching conditions.

Python/compile.c

+1
Original file line numberDiff line numberDiff line change
@@ -2930,6 +2930,7 @@ compiler_jump_if(struct compiler *c, expr_ty e, basicblock *next, int cond)
29302930
return 1;
29312931
}
29322932
case Compare_kind: {
2933+
SET_LOC(c, e);
29332934
Py_ssize_t i, n = asdl_seq_LEN(e->v.Compare.ops) - 1;
29342935
if (n > 0) {
29352936
if (!check_compare(c, e)) {

0 commit comments

Comments
 (0)