False positive on comprehensions in class scope

Bug #1184732 reported by Ben Darnell
18
This bug affects 2 people
Affects Status Importance Assigned to Milestone
Pyflakes
Fix Released
Low
Unassigned

Bug Description

Pyflakes reports "undefined name A" on the third line of this code:

class C(object):
    A = [1, 2, 3]
    B = dict((i, str(i)) for i in A)

This construction works in every version of Python since at least 2.5. (real-world use case from which this was extracted: https://github.com/facebook/tornado/blob/master/tornado/options.py#L444)

Related branches

Revision history for this message
asmeurer (asmeurer) wrote :

Changing the except clause at line 444 to also catch ClassScope fixes it, i.e.,

diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index ed9381e..6ed7f9c 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -441,7 +441,7 @@ class Checker(object):
         importStarred = self.scope.importStarred
         for scope in self.scopeStack[-2:0:-1]:
             importStarred = importStarred or scope.importStarred
- if not isinstance(scope, FunctionScope):
+ if not isinstance(scope, (FunctionScope, ClassScope)):
                 continue
             try:
                 scope[name].used = (self.scope, node)

But I'm not sure what the implications of this change are. It seems to lead to some test failures (which I cannot understand how to read).

Revision history for this message
Florent (florent.x) wrote :

Another test case from issue #1190075 (marked duplicate)

class A:
    T = range(10)

    X = {x for x in T}
    Y = {x:x for x in T}
    Z = (x for x in T)
    L = [x for x in T]

I tried the patch proposed by @asmeurer and it fixes the issue.
However it gives a failure in another part of the test suite. Under investigation...

Revision history for this message
Florent (florent.x) wrote :

Patch attached.

Changed in pyflakes:
importance: Undecided → Low
milestone: none → 0.7.x
status: New → Confirmed
Florent (florent.x)
Changed in pyflakes:
status: Confirmed → Fix Committed
Florent (florent.x)
Changed in pyflakes:
status: Fix Committed → Fix Released
To post a comment you must log in.
This report contains Public information  
Everyone can see this information.

Duplicates of this bug

Other bug subscribers

Remote bug watches

Bug watches keep track of this bug in other bug trackers.