Commits

Anonymous committed 927c212

Replaced compiler module with ast module, __builtins__ with builtins
Fixed invalid syntax (print as statement, exception name bounding with comma, itermethod with method etc).
Replaced the attribute id from LAMBDA method with the attribute arg.

Comments (0)

Files changed (4)

     http://nedbatchelder.com/blog/200803/python_code_complexity_microtool.html
     MIT License.
 """
-import compiler
+import ast
 import optparse
 import sys
 
         self.look = look
 
     def to_dot(self):
-        print 'node [shape=%s,label="%s"] %d;' % \
+        print('node [shape=%s,label="%s"] %d;' % \
                 (self.look, self.name, self.dot_id())
+              )
 
     def dot_id(self):
         return id(self)
         self.nodes.setdefault(n1, []).append(n2)
 
     def to_dot(self):
-        print 'subgraph {'
+        print('subgraph {')
         for node in self.nodes:
             node.to_dot()
         for node, nexts in self.nodes.items():
             for next in nexts:
-                print '%s -- %s;' % (node.dot_id(), next.dot_id())
-        print '}'
+                print('%s -- %s;' % (node.dot_id(), next.dot_id()))
+        print('}')
 
     def complexity(self):
         """ Return the McCabe complexity for the graph.
         return num_edges - num_nodes + 2
 
 
-class PathGraphingAstVisitor(compiler.visitor.ASTVisitor):
+class PathGraphingAstVisitor(ast.NodeVisitor):
     """ A visitor for a parsed Abstract Syntax Tree which finds executable
         statements.
     """
 
     def __init__(self):
-        compiler.visitor.ASTVisitor.__init__(self)
+        ast.NodeVisitor.__init__(self)
         self.classname = ""
         self.graphs = {}
         self.reset()
 def get_code_complexity(code, min=7, filename='stdin'):
     complex = []
     try:
-        ast = compiler.parse(code)
+        tree = ast.parse(code)
     except AttributeError as e:
-        print >> sys.stderr, "Unable to parse %s: %s" % (filename, e)
+        print("Unable to parse %s: %s" % (filename, e), file=sys.stderr)
         return 0
 
     visitor = PathGraphingAstVisitor()
-    visitor.preorder(ast, visitor)
+    visitor.preorder(tree, visitor)
     for graph in visitor.graphs.values():
         if graph is None:
             # ?
     options, args = opar.parse_args(argv)
 
     text = open(args[0], "rU").read() + '\n\n'
-    ast = compiler.parse(text)
+    tree = ast.parse(text)
     visitor = PathGraphingAstVisitor()
-    visitor.preorder(ast, visitor)
+    visitor.preorder(tree, visitor)
 
     if options.dot:
-        print 'graph {'
+        print('graph {')
         for graph in visitor.graphs.values():
             if graph.complexity() >= options.min:
                 graph.to_dot()
-        print '}'
+        print('}')
     else:
         for graph in visitor.graphs.values():
             if graph.complexity() >= options.min:
-                print graph.name, graph.complexity()
+                print(graph.name, graph.complexity())
 
 
 if __name__ == '__main__':

flake8/pyflakes.py

 # (c) 2005-2010 Divmod, Inc.
 # See LICENSE file for details
 
-import __builtin__
+import builtins
 import os.path
 import _ast
 import sys
                 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
             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,
     @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, 'U').read() + '\n', filename)
+    except IOError as msg:
+        print("%s: %s" % (filename, msg.args[1]), file=sys.stderr)
         return 1
 
 
     # 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 + "^")
 
         return 1
     else:
         # Okay, it's syntactically valid.  Now check it.
         w = Checker(tree, filename)
-        w.messages.sort(lambda a, b: cmp(a.lineno, b.lineno))
+        w.messages.sort(key=lambda a: a.lineno)
         valid_warnings = 0
 
         for warning in w.messages:
             if skip_warning(warning):
                 continue
-            print warning
+            print(warning)
             valid_warnings += 1
 
         return valid_warnings
 
 def _get_files(repo, **kwargs):
     seen = set()
-    for rev in xrange(repo[kwargs['node']], len(repo)):
+    for rev in range(repo[kwargs['node']], len(repo)):
         for file_ in repo[rev].files():
             file_ = os.path.join(repo.root, file_)
             if file_ in seen or not os.path.exists(file_):

flake8/tests/test_mccabe.py

 import unittest
 import sys
-from StringIO import StringIO
+from io import StringIO
 
 from flake8.mccabe import get_code_complexity