Skip to content

Inconsistent scope search in comprehensions #127542

@Tikkoneus

Description

@Tikkoneus

Bug report

Bug description:

class Foo:
    A = [1,2,3]
    B = [2,3,4]

    FOO = [x for x in A]           # works
    BAR = [x for x in A if x in B] # NameError 'B' is not defined??
    BAZ = [x for x in A if x in A] # NameError 'A' is not defined??
    BAT = (lambda A,B: [x for x in A if x in B])(A,B) # explicit binding works

BAR produces:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    class Foo:
    ^^^^^^^^^^
    ...<6 lines>...
        BAT = (lambda A,B: [x for x in A if x in B])(A,B) # explicit binding works
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "test.py", line 6, in Foo
    BAR = [x for x in A if x in B] # NameError 'B' is not defined??
                                ^
NameError: name 'B' is not defined

and, similarly, BAZ produces

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    class Foo:
    ^^^^^^^^^^
    ...<6 lines>...
        BAT = (lambda A,B: [x for x in A if x in B])(A,B) # explicit binding works
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "test.py", line 7, in Foo
    BAZ = [x for x in A if x in A] # NameError 'A' is not defined??
                                ^
NameError: name 'A' is not defined

It appears that with no conditional the comprehension scope searches the class scope; but variable references within a conditional are not resolved using the same scope search (it appears to LOAD_GLOBAL A). Note that this latter behavior does not affect the resolution of variables outside the conditional expression in the same comprehension.

Also tested on 3.6 and 3.8, though those aren't options in this form.

CPython versions tested on:

3.9, 3.13

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions