Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-104357: fix inlined comprehensions that close over iteration var #104368

Merged
merged 2 commits into from
May 11, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
10 changes: 10 additions & 0 deletions Lib/test/test_listcomps.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,16 @@ def test_inner_cell_shadows_outer(self):
outputs = {"y": [4, 4, 4, 4, 4], "i": 20}
self._check_in_scopes(code, outputs)

def test_inner_cell_shadows_outer_no_store(self):
carljm marked this conversation as resolved.
Show resolved Hide resolved
code = """
def f(x):
return [lambda: x for x in range(x)], x
fns, x = f(2)
y = [fn() for fn in fns]
"""
outputs = {"y": [1, 1], "x": 2}
self._check_in_scopes(code, outputs)

def test_closure_can_jump_over_comp_scope(self):
code = """
items = [(lambda: y) for i in range(5)]
Expand Down
19 changes: 13 additions & 6 deletions Python/symtable.c
Original file line number Diff line number Diff line change
Expand Up @@ -607,12 +607,19 @@ inline_comprehension(PySTEntryObject *ste, PySTEntryObject *comp,
SET_SCOPE(scopes, k, scope);
}
else {
// free vars in comprehension that are locals in outer scope can
// now simply be locals, unless they are free in comp children
if ((PyLong_AsLong(existing) & DEF_BOUND) &&
!is_free_in_any_child(comp, k)) {
if (PySet_Discard(comp_free, k) < 0) {
return 0;
if (PyLong_AsLong(existing) & DEF_BOUND) {
// cell vars in comprehension that are locals in outer scope
// must be promoted to cell so u_cellvars isn't wrong
if (scope == CELL && ste->ste_type == FunctionBlock) {
SET_SCOPE(scopes, k, scope);
}

// free vars in comprehension that are locals in outer scope can
// now simply be locals, unless they are free in comp children
if (!is_free_in_any_child(comp, k)) {
if (PySet_Discard(comp_free, k) < 0) {
return 0;
}
}
}
}
Expand Down