Skip to content

Commit 03cd447

Browse files
[3.13] gh-119666: fix multiple class-scope comprehensions referencing __class__ (GH-120295) (#120299)
1 parent c15f94d commit 03cd447

File tree

3 files changed

+36
-13
lines changed

3 files changed

+36
-13
lines changed

Lib/test/test_listcomps.py

+25
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,31 @@ def test_references___class__(self):
168168
"""
169169
self._check_in_scopes(code, raises=NameError)
170170

171+
def test_references___class___defined(self):
172+
code = """
173+
__class__ = 2
174+
res = [__class__ for x in [1]]
175+
"""
176+
self._check_in_scopes(
177+
code, outputs={"res": [2]}, scopes=["module", "function"])
178+
self._check_in_scopes(code, raises=NameError, scopes=["class"])
179+
180+
def test_references___class___enclosing(self):
181+
code = """
182+
__class__ = 2
183+
class C:
184+
res = [__class__ for x in [1]]
185+
res = C.res
186+
"""
187+
self._check_in_scopes(code, raises=NameError)
188+
189+
def test_super_and_class_cell_in_sibling_comps(self):
190+
code = """
191+
[super for _ in [1]]
192+
[__class__ for _ in [1]]
193+
"""
194+
self._check_in_scopes(code, raises=NameError)
195+
171196
def test_inner_cell_shadows_outer(self):
172197
code = """
173198
items = [(lambda: i) for i in range(5)]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix a compiler crash in the case where two comprehensions in class scope both reference ``__class__``.

Python/symtable.c

+10-13
Original file line numberDiff line numberDiff line change
@@ -780,22 +780,19 @@ inline_comprehension(PySTEntryObject *ste, PySTEntryObject *comp,
780780
if (existing == NULL && PyErr_Occurred()) {
781781
return 0;
782782
}
783+
// __class__ is never allowed to be free through a class scope (see
784+
// drop_class_free)
785+
if (scope == FREE && ste->ste_type == ClassBlock &&
786+
_PyUnicode_EqualToASCIIString(k, "__class__")) {
787+
scope = GLOBAL_IMPLICIT;
788+
if (PySet_Discard(comp_free, k) < 0) {
789+
return 0;
790+
}
791+
remove_dunder_class = 1;
792+
}
783793
if (!existing) {
784794
// name does not exist in scope, copy from comprehension
785795
assert(scope != FREE || PySet_Contains(comp_free, k) == 1);
786-
if (scope == FREE && ste->ste_type == ClassBlock &&
787-
_PyUnicode_EqualToASCIIString(k, "__class__")) {
788-
// if __class__ is unbound in the enclosing class scope and free
789-
// in the comprehension scope, it needs special handling; just
790-
// letting it be marked as free in class scope will break due to
791-
// drop_class_free
792-
scope = GLOBAL_IMPLICIT;
793-
only_flags &= ~DEF_FREE;
794-
if (PySet_Discard(comp_free, k) < 0) {
795-
return 0;
796-
}
797-
remove_dunder_class = 1;
798-
}
799796
PyObject *v_flags = PyLong_FromLong(only_flags);
800797
if (v_flags == NULL) {
801798
return 0;

0 commit comments

Comments
 (0)