Skip to content

Commit 094394a

Browse files
[3.13] gh-128396: Fix a crash when inline comprehension has the same … (#130311)
[3.13] gh-128396: Fix a crash when inline comprehension has the same local variable as the outside scope (GH-130235) (cherry picked from commit ccf1732)
1 parent 5907cd6 commit 094394a

File tree

3 files changed

+16
-2
lines changed

3 files changed

+16
-2
lines changed

Lib/test/test_frame.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,12 @@ def f():
298298
self.assertEqual(x, 2)
299299
self.assertEqual(y, 3)
300300

301+
def test_closure_with_inline_comprehension(self):
302+
lambda: k
303+
k = 1
304+
lst = [locals() for k in [0]]
305+
self.assertEqual(lst[0]['k'], 0)
306+
301307
def test_as_dict(self):
302308
x = 1
303309
y = 2
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a crash that occurs when calling :func:`locals` inside an inline comprehension that uses the same local variable as the outer frame scope where the variable is a free or cell var.

Objects/frameobject.c

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,15 @@ framelocalsproxy_getval(_PyInterpreterFrame *frame, PyCodeObject *co, int i)
3535
if (kind == CO_FAST_FREE || kind & CO_FAST_CELL) {
3636
// The cell was set when the frame was created from
3737
// the function's closure.
38-
assert(PyCell_Check(value));
39-
cell = value;
38+
// GH-128396: With PEP 709, it's possible to have a fast variable in
39+
// an inlined comprehension that has the same name as the cell variable
40+
// in the frame, where the `kind` obtained from frame can not guarantee
41+
// that the variable is a cell.
42+
// If the variable is not a cell, we are okay with it and we can simply
43+
// return the value.
44+
if (PyCell_Check(value)) {
45+
cell = value;
46+
}
4047
}
4148

4249
if (cell != NULL) {

0 commit comments

Comments
 (0)