Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 5914d77

Browse files
committed
remove assumption that class scopes can't have cellvars
1 parent baacf5f commit 5914d77

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

Lib/test/test_listcomps.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,17 @@ def test_lambdas_with_free_var(self):
143143
outputs = {"y": [4, 4, 4, 4, 4]}
144144
self._check_in_scopes(code, outputs)
145145

146+
def test_class_scope_free_var_with_class_cell(self):
147+
class C:
148+
def method(self):
149+
super()
150+
return __class__
151+
items = [(lambda: i) for i in range(5)]
152+
y = [x() for x in items]
153+
154+
self.assertEqual(C.y, [4, 4, 4, 4, 4])
155+
self.assertIs(C().method(), C)
156+
146157
def test_inner_cell_shadows_outer(self):
147158
code = """
148159
items = [(lambda: i) for i in range(5)]

Python/compile.c

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1245,9 +1245,7 @@ compiler_enter_scope(struct compiler *c, identifier name,
12451245
/* Cook up an implicit __class__ cell. */
12461246
int res;
12471247
assert(u->u_scope_type == COMPILER_SCOPE_CLASS);
1248-
assert(PyDict_GET_SIZE(u->u_metadata.u_cellvars) == 0);
1249-
res = PyDict_SetItem(u->u_metadata.u_cellvars, &_Py_ID(__class__),
1250-
_PyLong_GetZero());
1248+
res = dict_add_o(u->u_metadata.u_cellvars, &_Py_ID(__class__));
12511249
if (res < 0) {
12521250
compiler_unit_free(u);
12531251
return ERROR;
@@ -2245,7 +2243,6 @@ compiler_class(struct compiler *c, stmt_ty s)
22452243
compiler_exit_scope(c);
22462244
return ERROR;
22472245
}
2248-
assert(i == 0);
22492246
ADDOP_I(c, NO_LOCATION, LOAD_CLOSURE, i);
22502247
ADDOP_I(c, NO_LOCATION, COPY, 1);
22512248
if (compiler_nameop(c, NO_LOCATION, &_Py_ID(__classcell__), Store) < 0) {

0 commit comments

Comments
 (0)