Skip to content

Commit d62cbba

Browse files
[3.12] gh-120722: Set position on RETURN_VALUE in lambda (GH-120724) (#120739)
(cherry picked from commit d8f27cb)
1 parent cde976d commit d62cbba

File tree

3 files changed

+31
-2
lines changed

3 files changed

+31
-2
lines changed

Lib/test/test_compile.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import textwrap
1111
import warnings
1212
from test import support
13-
from test.support import (script_helper, requires_debug_ranges,
13+
from test.support import (script_helper, requires_debug_ranges, run_code,
1414
requires_specialization, C_RECURSION_LIMIT)
1515
from test.support.os_helper import FakePath
1616

@@ -1829,6 +1829,33 @@ def test_load_super_attr(self):
18291829
code, "LOAD_GLOBAL", line=3, end_line=3, column=4, end_column=9
18301830
)
18311831

1832+
def test_lambda_return_position(self):
1833+
snippets = [
1834+
"f = lambda: x",
1835+
"f = lambda: 42",
1836+
"f = lambda: 1 + 2",
1837+
"f = lambda: a + b",
1838+
]
1839+
for snippet in snippets:
1840+
with self.subTest(snippet=snippet):
1841+
lamb = run_code(snippet)["f"]
1842+
positions = lamb.__code__.co_positions()
1843+
# assert that all positions are within the lambda
1844+
for i, pos in enumerate(positions):
1845+
with self.subTest(i=i, pos=pos):
1846+
start_line, end_line, start_col, end_col = pos
1847+
if i == 0 and start_col == end_col == 0:
1848+
# ignore the RESUME in the beginning
1849+
continue
1850+
self.assertEqual(start_line, 1)
1851+
self.assertEqual(end_line, 1)
1852+
code_start = snippet.find(":") + 2
1853+
code_end = len(snippet)
1854+
self.assertGreaterEqual(start_col, code_start)
1855+
self.assertLessEqual(end_col, code_end)
1856+
self.assertGreaterEqual(end_col, start_col)
1857+
self.assertLessEqual(end_col, code_end)
1858+
18321859

18331860
class TestExpressionStackSize(unittest.TestCase):
18341861
# These tests check that the computed stack size for a code object
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Correctly set the bytecode position on return instructions within lambdas.
2+
Patch by Jelle Zijlstra.

Python/compile.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2966,7 +2966,7 @@ compiler_lambda(struct compiler *c, expr_ty e)
29662966
co = optimize_and_assemble(c, 0);
29672967
}
29682968
else {
2969-
location loc = LOCATION(e->lineno, e->lineno, 0, 0);
2969+
location loc = LOC(e->v.Lambda.body);
29702970
ADDOP_IN_SCOPE(c, loc, RETURN_VALUE);
29712971
co = optimize_and_assemble(c, 1);
29722972
}

0 commit comments

Comments
 (0)