Commits

Torsten Marek committed 14f9bae

Some work on making pylint work on Python 3 without 2to3.

Comments (0)

Files changed (5)

checkers/utils.py

     try:
         if position is not None and not isinstance(callfunc_node.args[position], astroid.Keyword):
             return callfunc_node.args[position]
-    except IndexError, error:
+    except IndexError as error:
         raise NoSuchArgumentError(error)
     if keyword:
         for arg in callfunc_node.args:
 
   Display help messages about given message identifiers and exit.
 """
+from __future__ import print_function
 
 # import this first to avoid builtin namespace pollution
 from pylint.checkers import utils #pylint: disable=unused-import
         try:
             BaseTokenChecker.set_option(self, optname, value, action, optdict)
         except UnsupportedAction:
-            print >> sys.stderr, 'option %s can\'t be read from config file' % \
-                  optname
+            print('option %s can\'t be read from config file' % \
+                  optname, file=sys.stderr)
 
     def register_reporter(self, reporter_class):
         self._reporters[reporter_class.name] = reporter_class
         """return a ast(roid) representation for a module"""
         try:
             return MANAGER.ast_from_file(filepath, modname, source=True)
-        except SyntaxError, ex:
+        except SyntaxError as ex:
             self.add_message('syntax-error', line=ex.lineno, args=ex.msg)
-        except AstroidBuildingException, ex:
+        except AstroidBuildingException as ex:
             self.add_message('parse-error', args=ex)
-        except Exception, ex:
+        except Exception as ex:
             import traceback
             traceback.print_exc()
             self.add_message('astroid-error', args=(ex.__class__, ex))
         # call raw checkers if possible
         try:
             tokens = tokenize_module(astroid)
-        except tokenize.TokenError, ex:
+        except tokenize.TokenError as ex:
             self.add_message('syntax-error', line=ex.args[1][0], args=ex.args[0])
             return
 
         evaluation = self.config.evaluation
         try:
             note = eval(evaluation, {}, self.stats)
-        except Exception, ex:
+        except Exception as ex:
             msg = 'An exception occurred while rating: %s' % ex
         else:
             stats['global_note'] = note
                 'rcfile':       (self.cb_set_rcfile, True),
                 'load-plugins': (self.cb_add_plugins, True),
                 })
-        except ArgumentPreprocessingError, ex:
-            print >> sys.stderr, ex
+        except ArgumentPreprocessingError as ex:
+            print(ex, file=sys.stderr)
             sys.exit(32)
 
         self.linter = linter = self.LinterClass((
             linter.set_reporter(reporter)
         try:
             args = linter.load_command_line_configuration(args)
-        except SystemExit, exc:
+        except SystemExit as exc:
             if exc.code == 2: # bad options
                 exc.code = 32
             raise
         if not args:
-            print linter.help()
+            print(linter.help())
             sys.exit(32)
         # insert current working directory to the python path to have a correct
         # behaviour
         linter.prepare_import_path(args)
         if self.linter.config.profile:
-            print >> sys.stderr, '** profiled run'
+            print('** profiled run', file=sys.stderr)
             import cProfile, pstats
             cProfile.runctx('linter.check(%r)' % args, globals(), locals(),
                             'stones.prof')

reporters/__init__.py

     def cmp(a, b):
         return (a > b) - (a < b)
 
-if sys.version_info < (2, 6):
-    import stringformat
-    stringformat.init(True)
-
 def diff_string(old, new):
     """given a old and new int value, return a string representing the
     difference

test/unittest_checker_base.py

 
     @set_config(attr_rgx=re.compile('[A-Z]+'))
     def test_property_names(self):
-        if sys.version_info < (2, 6):
-            self.skip('abc module does not exist on 2.5')
         # If a method is annotated with @property, it's name should
         # match the attr regex. Since by default the attribute regex is the same
         # as the method regex, we override it here.
 """some various utilities and helper classes, most of them used in the
 main pylint class
 """
+from __future__ import print_function
 
 import collections
 import os
     'E' : 'error',
     'F' : 'fatal'
     }
-MSG_TYPES_LONG = dict([(v, k) for k, v in MSG_TYPES.iteritems()])
+MSG_TYPES_LONG = {v: k for k, v in MSG_TYPES.iteritems()}
 
 MSG_TYPES_STATUS = {
     'I' : 0,
         for checker in self.get_checkers():
             if checker.name == 'master':
                 prefix = 'Main '
-                print "Options"
-                print '-------\n'
+                print("Options")
+                print('-------\n')
                 if checker.options:
                     for section, options in checker.options_by_section():
                         if section is None:
                             title = 'General options'
                         else:
                             title = '%s options' % section.capitalize()
-                        print title
-                        print '~' * len(title)
+                        print(title)
+                        print('~' * len(title))
                         rest_format_section(sys.stdout, None, options)
-                        print
+                        print()
             else:
                 try:
                     by_checker[checker.name][0] += checker.options_and_values()
         for checker, (options, msgs, reports) in by_checker.iteritems():
             prefix = ''
             title = '%s checker' % checker
-            print title
-            print '-' * len(title)
-            print
+            print(title)
+            print('-' * len(title))
+            print()
             if options:
                 title = 'Options'
-                print title
-                print '~' * len(title)
+                print(title)
+                print('~' * len(title))
                 rest_format_section(sys.stdout, None, options)
-                print
+                print()
             if msgs:
                 title = ('%smessages' % prefix).capitalize()
-                print title
-                print '~' * len(title)
+                print(title)
+                print('~' * len(title))
                 for msgid, msg in sorted(msgs.iteritems(),
-                                         key=lambda (k, v): (_MSG_ORDER.index(k[0]), k)):
+                                         key=lambda kv: (_MSG_ORDER.index(kv[0][0]), kv[1])):
                     msg = build_message_def(checker, msgid, msg)
-                    print msg.format_help(checkerref=False)
-                print
+                    print(msg.format_help(checkerref=False))
+                print()
             if reports:
                 title = ('%sreports' % prefix).capitalize()
-                print title
-                print '~' * len(title)
+                print(title)
+                print('~' * len(title))
                 for report in reports:
-                    print ':%s: %s' % report[:2]
-                print
-            print
+                    print(':%s: %s' % report[:2])
+                print()
+            print()
 
 
 class FileState(object):
         """display help messages for the given message identifiers"""
         for msgid in msgids:
             try:
-                print self.check_message_id(msgid).format_help(checkerref=True)
-                print
-            except UnknownMessage, ex:
-                print ex
-                print
+                print(self.check_message_id(msgid).format_help(checkerref=True))
+                print()
+            except UnknownMessage as ex:
+                print(ex)
+                print()
                 continue
 
     def list_messages(self):
         for msg in msgs:
             if not msg.may_be_emitted():
                 continue
-            print msg.format_help(checkerref=False)
-        print
+            print(msg.format_help(checkerref=False))
+        print()
 
 
 class ReportsHandlerMixIn(object):
                 if filepath is None:
                     errors.append({'key' : 'ignored-builtin-module', 'mod': modname})
                     continue
-            except (ImportError, SyntaxError), ex:
+            except (ImportError, SyntaxError) as ex:
                 # FIXME p3k : the SyntaxError is a Python bug and should be
                 # removed as soon as possible http://bugs.python.org/issue10588
                 errors.append({'key': 'fatal', 'mod': modname, 'ex': ex})
             except ValueError:
                 # empty module name (usually emacs auto-save files)
                 continue
-            except ImportError, exc:
+            except ImportError as exc:
                 print >> sys.stderr, "Problem importing module %s: %s" % (filename, exc)
             else:
                 if hasattr(module, 'register'):