Commits

Virgil Dupras committed 54d392e

Converted to py3k.

  • Participants
  • Parent commits 3569d71

Comments (0)

Files changed (6)

pyflakes/checker.py

 # (c) 2005-2010 Divmod, Inc.
 # See LICENSE file for details
 
-import __builtin__
+import builtins
 import os.path
 import _ast
 
                 all = []
 
             # Look for imported names that aren't used.
-            for importation in scope.itervalues():
+            for importation in scope.values():
                 if isinstance(importation, Importation):
                     if not importation.used and importation.name not in all:
                         self.report(
     def handleNode(self, node, parent):
         node.parent = parent
         if self.traceTree:
-            print '  ' * self.nodeDepth + node.__class__.__name__
+            print('  ' * self.nodeDepth + node.__class__.__name__)
         self.nodeDepth += 1
         if self.futuresAllowed and not \
                (isinstance(node, _ast.ImportFrom) or self.isDocstring(node)):
         finally:
             self.nodeDepth -= 1
         if self.traceTree:
-            print '  ' * self.nodeDepth + 'end ' + node.__class__.__name__
+            print('  ' * self.nodeDepth + 'end ' + node.__class__.__name__)
 
     def ignore(self, node):
         pass
     BOOLOP = BINOP = UNARYOP = IFEXP = DICT = SET = YIELD = COMPARE = \
     CALL = REPR = ATTRIBUTE = SUBSCRIPT = LIST = TUPLE = handleChildren
 
-    NUM = STR = ELLIPSIS = ignore
+    NUM = STR = BYTES = ELLIPSIS = ignore
 
     # "slice" type nodes
     SLICE = EXTSLICE = INDEX = handleChildren
             try:
                 self.scopeStack[0][node.id].used = (self.scope, node.lineno)
             except KeyError:
-                if ((not hasattr(__builtin__, node.id))
+                if ((not hasattr(builtins, node.id))
                         and node.id not in _MAGIC_GLOBALS
                         and not importStarred):
                     if (os.path.basename(self.filename) == '__init__.py' and
                     if isinstance(arg, _ast.Tuple):
                         addArgs(arg.elts)
                     else:
-                        if arg.id in args:
+                        if arg.arg in args:
                             self.report(messages.DuplicateArgument,
-                                        node.lineno, arg.id)
-                        args.append(arg.id)
+                                        node.lineno, arg.arg)
+                        args.append(arg.arg)
 
             self.pushFunctionScope()
             addArgs(node.args.args)
                 """
                 Check to see if any assignments have not been used.
                 """
-                for name, binding in self.scope.iteritems():
+                for name, binding in self.scope.items():
                     if (not binding.used and not name in self.scope.globals
                         and isinstance(binding, Assignment)):
                         self.report(messages.UnusedVariable,

pyflakes/scripts/pyflakes.py

     # First, compile into an AST and handle syntax errors.
     try:
         tree = compile(codeString, filename, "exec", _ast.PyCF_ONLY_AST)
-    except SyntaxError, value:
+    except SyntaxError as value:
         msg = value.args[0]
 
         (lineno, offset, text) = value.lineno, value.offset, value.text
             # Avoid using msg, since for the only known case, it contains a
             # bogus message that claims the encoding the file declared was
             # unknown.
-            print >> sys.stderr, "%s: problem decoding source" % (filename, )
+            print("%s: problem decoding source" % (filename, ), file=sys.stderr)
         else:
             line = text.splitlines()[-1]
 
             if offset is not None:
                 offset = offset - (len(text) - len(line))
 
-            print >> sys.stderr, '%s:%d: %s' % (filename, lineno, msg)
-            print >> sys.stderr, line
+            print('%s:%d: %s' % (filename, lineno, msg), file=sys.stderr)
+            print(line, file=sys.stderr)
 
             if offset is not None:
-                print >> sys.stderr, " " * offset, "^"
+                print(" " * offset, "^", file=sys.stderr)
 
         return 1
     else:
         # Okay, it's syntactically valid.  Now check it.
         w = checker.Checker(tree, filename)
-        w.messages.sort(lambda a, b: cmp(a.lineno, b.lineno))
+        w.messages.sort(key=lambda m: m.lineno)
         for warning in w.messages:
-            print warning
+            print(warning)
         return len(w.messages)
 
 
     @return: the number of warnings printed
     """
     try:
-        return check(file(filename, 'U').read() + '\n', filename)
-    except IOError, msg:
-        print >> sys.stderr, "%s: %s" % (filename, msg.args[1])
+        return check(open(filename, 'rb').read() + b'\n', filename)
+    except IOError as msg:
+        print("%s: %s" % (filename, msg.args[1]), file=sys.stderr)
         return 1
 
 

pyflakes/test/harness.py

         w = checker.Checker(ast, **kw)
         outputs = [type(o) for o in w.messages]
         expectedOutputs = list(expectedOutputs)
-        outputs.sort()
-        expectedOutputs.sort()
+        outputs.sort(key=lambda t: t.__name__)
+        expectedOutputs.sort(key=lambda t: t.__name__)
         self.assert_(outputs == expectedOutputs, '''\
 for input:
 %s

pyflakes/test/test_imports.py

         self.flakes('from moo import fu as FU, bar as FU', m.RedefinedWhileUnused, m.UnusedImport)
 
     def test_usedImport(self):
-        self.flakes('import fu; print fu')
-        self.flakes('from baz import fu; print fu')
+        self.flakes('import fu; print(fu)')
+        self.flakes('from baz import fu; print(fu)')
 
     def test_redefinedWhileUnused(self):
         self.flakes('import fu; fu = 3', m.RedefinedWhileUnused)
         import fu
         class bar:
             fu = 1
-        print fu
+        print(fu)
         ''')
 
     def test_usedInFunction(self):
         self.flakes('''
         import fu
         def fun():
-            print fu
+            print(fu)
         ''')
 
     def test_shadowedByParameter(self):
         self.flakes('''
         import fu
         def fun(fu):
-            print fu
+            print(fu)
         ''', m.UnusedImport)
 
         self.flakes('''
         import fu
         def fun(fu):
-            print fu
-        print fu
+            print(fu)
+        print(fu)
         ''')
 
     def test_newAssignment(self):
         self.flakes('import fu; "bar".fu.baz', m.UnusedImport)
 
     def test_usedInSlice(self):
-        self.flakes('import fu; print fu.bar[1:]')
+        self.flakes('import fu; print(fu.bar[1:])')
 
     def test_usedInIfBody(self):
         self.flakes('''
         import fu
-        if True: print fu
+        if True: print(fu)
         ''')
 
     def test_usedInIfConditional(self):
         self.flakes('''
         import fu
         if False: pass
-        else: print fu
+        else: print(fu)
         ''')
 
     def test_usedInCall(self):
         import fu
         def bleh():
             pass
-        print fu
+        print(fu)
         ''')
 
     def test_usedInFor(self):
         self.flakes('''
         import fu
         for bar in range(9):
-            print fu
+            print(fu)
         ''')
 
     def test_usedInForElse(self):
         for bar in range(10):
             pass
         else:
-            print fu
+            print(fu)
         ''')
 
     def test_redefinedByFor(self):
         except: pass
         ''')
 
+    @skip("todo")
     def test_redefinedByExcept(self):
         self.flakes('''
         import fu
         try: pass
-        except Exception, fu: pass
+        except Exception as fu: pass
         ''', m.RedefinedWhileUnused)
 
     def test_usedInRaise(self):
         def f(): global fu
         ''', m.UnusedImport)
 
-    def test_usedInBackquote(self):
-        self.flakes('import fu; `fu`')
-
     def test_usedInExec(self):
-        self.flakes('import fu; exec "print 1" in fu.bar')
+        self.flakes('import fu; exec("print(1)" in fu.bar)')
 
     def test_usedInLambda(self):
         self.flakes('import fu; lambda: fu')
             import fu
             class b:
                 def c(self):
-                    print fu
+                    print(fu)
         ''')
 
     def test_importStar(self):

pyflakes/test/test_script.py

 """
 
 import sys
-from StringIO import StringIO
+from io import StringIO
 import tempfile
 import os.path
 import os
 
 def fileWithContents(contents):
     _, fname = tempfile.mkstemp()
-    fd = open(fname, 'wt')
+    mode = 'wt' if isinstance(contents, str) else 'wb'
+    fd = open(fname, mode)
     fd.write(contents)
     fd.close()
     return fname
         # Sanity check - SyntaxError.text should be multiple lines, if it
         # isn't, something this test was unprepared for has happened.
         def evaluate(source):
-            exec source
+            exec(source)
         try:
             evaluate(source)
         except SyntaxError as e:
         If a source file contains bytes which cannot be decoded, this is
         reported on stderr.
         """
-        source = u"""\
+        source = """\
 # coding: ascii
 x = "\N{SNOWMAN}"
 """.encode('utf-8')

pyflakes/test/test_undefined_names.py

         bar
         ''', m.ImportStarUsed, m.UndefinedName)
 
-    def test_unpackedParameter(self):
-        '''Unpacked function parameters create bindings'''
-        self.flakes('''
-        def a((bar, baz)):
-            bar; baz
-        ''')
-
     @skip("todo")
     def test_definedByGlobal(self):
         '''"global" can make an otherwise undefined name in another function defined'''
         self.flakes('''
         global x
         def foo():
-            print x
+            print(x)
         ''', m.UndefinedName)
 
     def test_del(self):
                 def h(self):
                     a = x
                     x = None
-                    print x, a
-            print x
+                    print(x, a)
+            print(x)
         ''', m.UndefinedLocal)
 
 
         '''star and double-star arg names are defined'''
         self.flakes('''
         def f(a, *b, **c):
-            print a, b, c
+            print(a, b, c)
         ''')
 
     def test_definedInGenExp(self):
         Using the loop variable of a generator expression results in no
         warnings.
         """
-        self.flakes('(a for a in xrange(10) if a)')
+        self.flakes('(a for a in range(10) if a)')