diff --git a/Lib/test/test_listcomps.py b/Lib/test/test_listcomps.py index 3a6e62fe448724..e4d1c1900cd1f7 100644 --- a/Lib/test/test_listcomps.py +++ b/Lib/test/test_listcomps.py @@ -191,6 +191,16 @@ >>> test_func([1]) [1] + >>> def test_func(): + ... x = 1 + ... def g(): + ... [x for x in range(3)] + ... return x + ... g() + ... return x + >>> test_func() + 1 + """ diff --git a/Python/compile.c b/Python/compile.c index 545fd2f41972a5..16ff29ff33f173 100644 --- a/Python/compile.c +++ b/Python/compile.c @@ -5237,7 +5237,7 @@ push_inlined_comprehension_state(struct compiler *c, location loc, assert(PyLong_Check(outv)); long outsc = (PyLong_AS_LONG(outv) >> SCOPE_OFFSET) & SCOPE_MASK; int outer_global = (outsc == GLOBAL_IMPLICIT || outsc == GLOBAL_EXPLICIT); - if (outer_global || (outsc == CELL && scope == LOCAL)) { + if (outer_global || ((outsc == CELL || outsc == FREE) && scope == LOCAL)) { // If a name is global in the outer scope but local in the // comprehension scope, we need to keep it global in outer scope // but ensure the comprehension writes to the local, not the