PyCQA / PyCQA/pyflakes

Undefined comprehension variable in class body not caught

Open
#503 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
1.5k
Forks
190
Avg merge
8m
Merged PRs (30d)
13

Description

class Test:
    a = [1, 2, 3]
    b = [1, 2, 3]
    c = [i*j for i in a for j in b]

Pyflakes gives no errors here. But believe it or not, this raises a NameError

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    class Test:
  File "test.py", line 4, in Test
    c = [i*j for i in a for j in b]
  File "test.py", line 4, in <listcomp>
    c = [i*j for i in a for j in b]
NameError: name 'b' is not defined

The reason has to do with how Python treats the outermost comprehension iterable differently. See https://stackoverflow.com/questions/13905741/accessing-class-variables-from-a-list-comprehension-in-the-class-definition. Note that the following does not give any errors when executed

class Test:
    a = [1, 2, 3]
    b = [1, 2, 3]
    c = [i for i in a]

Contributor guide

No contributing guide indexed for this repository

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

No project file or test is named. Start by reproducing the class-body comprehension and tracing pyflakes' comprehension and scope analysis; compare the diagnostic for the undefined inner iterable with the valid single-iterable example. Done means the reported NameError case is flagged without incorrectly flagging the valid case.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.