Repository: PyCQA/pyflakes (python)

Issue:
On Python 3, __class__ can be used without self
*Original report by [icordasc](https://launchpad.net/~icordasc) (@sigmavirus24?) on [Launchpad](https://bugs.launchpad.net/bugs/1487725):*

------------------------------------

On Python 3, the following code raises a warning:

```python
class Test(object):
    def __init__(self):
        print(__class__.__name__)
        self.x = 1

t = Test()
```

This is actually valid Python 3 code, but PyFlakes doesn't quite understand that:

    test.py:3: undefined name '__class__'


Pull request description:
Support `__class__` without `self` in Python 3
This fixes #223.

I created this patch previously in:

https://github.com/PyCQA/pyflakes/commit/83ab002d6fab2b717df91e854624c6fdfd9b9213

But I deleted that branch for some reason. I can't recall why I disliked it enough to delete it. But since I can't remember, I'll commit it to a branch again for others to look at.

Patch:
diff --git a/pyflakes/checker.py b/pyflakes/checker.py
index baef833..9b39e6c 100644
--- a/pyflakes/checker.py
+++ b/pyflakes/checker.py
@@ -710,10 +710,14 @@ class Checker(object):
 
         # try enclosing function scopes and global scope
         for scope in self.scopeStack[-1::-1]:
-            # only generators used in a class scope can access the names
-            # of the class. this is skipped during the first iteration
-            if in_generators is False and isinstance(scope, ClassScope):
-                continue
+            if isinstance(scope, ClassScope):
+                if not PY2 and name == '__class__':
+                    return
+                elif in_generators is False:
+                    # only generators used in a class scope can access the
+                    # names of the class. this is skipped during the first
+                    # iteration
+                    continue
 
             try:
                 scope[name].used = (self.scope, node)


Test patch:
diff --git a/pyflakes/test/test_undefined_names.py b/pyflakes/test/test_undefined_names.py
index 3d19210..d53e529 100644
--- a/pyflakes/test/test_undefined_names.py
+++ b/pyflakes/test/test_undefined_names.py
@@ -799,6 +799,24 @@ class Test(TestCase):
         any(lambda: id(y) for x in range(10))
         ''', m.UndefinedName)
 
+    def test_dunderClass(self):
+        """
+        `__class__` is defined in class scope under Python 3, but is not
+        in Python 2.
+        """
+        code = '''
+        class Test(object):
+            def __init__(self):
+                print(__class__.__name__)
+                self.x = 1
+
+        t = Test()
+        '''
+        if version_info < (3,):
+            self.flakes(code, m.UndefinedName)
+        else:
+            self.flakes(code)
+
 
 class NameTests(TestCase):
     """