python / python/cpython

Wrong binding of closure variable with intervening list comprehension

Open
#121,377 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

3.12 3.13 3.14 type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:
def f(x):
    def g():
        print([x for x in range(10)])
        def h():
            print(x)
        return h
    print(x)
    return g
f(1)()()

The above had always bound x in h to the parameter of f. But it no longer works and somehow binds to a local in g, throwing the following error:

NameError: cannot access free variable 'x' where it is not associated with a value in enclosing scope
CPython versions tested on:

3.12

Operating systems tested on:

Linux, Windows

Linked PRs
  • gh-124696

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the closure and list-comprehension example on CPython 3.12 and compare its output with the reported NameError. Start by reviewing the scoping and compilation path implicated by the example, then inspect linked PR gh-124696. Done means the example binds x to f's parameter and completes without the error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.