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

Undefined comprehension variable in class body not caught #503

Open
asmeurer opened this issue Jan 9, 2020 · 3 comments
Open

Undefined comprehension variable in class body not caught #503

asmeurer opened this issue Jan 9, 2020 · 3 comments

Comments

@asmeurer
Copy link
Contributor

asmeurer commented Jan 9, 2020

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]
@asmeurer
Copy link
Contributor Author

Actually it doesn't even catch the simpler case

class Test2:
    x = 1
    a = [x for i in range(2)]
$python test.py
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    class Test2:
  File "test.py", line 8, in Test2
    a = [x for i in range(2)]
  File "test.py", line 8, in <listcomp>
    a = [x for i in range(2)]
NameError: name 'x' is not defined

@asottile
Copy link
Member

pretty sure pyflakes doesn't know at all about the ~special class scope -- but probably wouldn't be too difficult to add

@asmeurer
Copy link
Contributor Author

asmeurer commented Jan 10, 2020

It gets it right for normal nested functions (i.e., methods)

class Test3:
    x = 1
    def func(self):
        print(x) # pyflakes gives an undefined name warning here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants