Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
16 changes: 16 additions & 0 deletions Lib/test/test_listcomps.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,22 @@ def test_references___class__(self):
"""
self._check_in_scopes(code, raises=NameError)

def test_lambda_in_comprehension_references___class__(self):
# gh-150700: lambda in class-scope comprehension referencing __class__
# must compile without SystemError and raise NameError at runtime
# (__class__ cell is not yet filled during class body execution).
code = """
res = [(lambda: __class__)() for _ in [1]]
"""
self._check_in_scopes(code, raises=NameError)

def test_lambda_in_comprehension_references___classdict__(self):
# gh-150700: lambda in class-scope comprehension referencing __classdict__
# must compile without SystemError; __classdict__ is available at runtime.
class _C:
res = [(lambda: __classdict__)() for _ in [1]]
self.assertIn("res", _C.res[0])
Comment thread
johnslavik marked this conversation as resolved.
Outdated

def test_references___class___defined(self):
code = """
__class__ = 2
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a :exc:`SystemError` when compiling a class-scope comprehension containing
a ``lambda`` that references ``__class__``, ``__classdict__``, or
``__conditional_annotations__``. Patch by Bartosz Sławecki.
Comment thread
johnslavik marked this conversation as resolved.
13 changes: 9 additions & 4 deletions Python/symtable.c
Original file line number Diff line number Diff line change
Expand Up @@ -834,17 +834,22 @@ inline_comprehension(PySTEntryObject *ste, PySTEntryObject *comp,
return 0;
}
// __class__, __classdict__ and __conditional_annotations__ are
// never allowed to be free through a class scope (see
// drop_class_free)
// not allowed to be free through a class scope (see
// drop_class_free) unless children scopes need it
if (scope == FREE && ste->ste_type == ClassBlock &&
(_PyUnicode_EqualToASCIIString(k, "__class__") ||
_PyUnicode_EqualToASCIIString(k, "__classdict__") ||
_PyUnicode_EqualToASCIIString(k, "__conditional_annotations__"))) {
scope = GLOBAL_IMPLICIT;
if (PySet_Discard(comp_free, k) < 0) {
int child_needs_free = is_free_in_any_child(comp, k);
if (child_needs_free < 0) {
return 0;
}

if (!child_needs_free) {
if (PySet_Discard(comp_free, k) < 0) {
return 0;
}
}
if (_PyUnicode_EqualToASCIIString(k, "__class__")) {
remove_dunder_class = 1;
}
Expand Down
Loading