eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleFixer.py

branch
maintenance
changeset 8273
698ae46f40a4
parent 8043
0acf98cd089a
parent 8259
2bbec88047dd
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleFixer.py	Fri Apr 02 11:59:41 2021 +0200
+++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleFixer.py	Sat May 01 14:27:20 2021 +0200
@@ -10,14 +10,13 @@
 import os
 import re
 import tokenize
+import contextlib
 from io import StringIO
 
 # CodeStyleCheckerDialog tries to import FixableCodeStyleIssues which fails
 # under Python3. So ignore it.
-try:
+with contextlib.suppress(ImportError):
     import pycodestyle
-except ImportError:
-    pass
 
 FixableCodeStyleIssues = [
     "D111", "D112", "D121", "D131", "D141", "D142",
@@ -38,7 +37,7 @@
 ]
 
 
-class CodeStyleFixer(object):
+class CodeStyleFixer:
     """
     Class implementing a fixer for certain code style issues.
     """
@@ -71,7 +70,7 @@
             anything
         @type bool
         """
-        super(CodeStyleFixer, self).__init__()
+        super().__init__()
         
         self.__filename = filename
         self.__origName = ""
@@ -209,16 +208,10 @@
                 bfn = '{0}~'.format(os.path.realpath(self.__filename))
             else:
                 bfn = '{0}~'.format(self.__filename)
-            try:
+            with contextlib.suppress(OSError):
                 os.remove(bfn)
-            except OSError:
-                # if there was an error, ignore it
-                pass
-            try:
+            with contextlib.suppress(OSError):
                 os.rename(self.__filename, bfn)
-            except OSError:
-                # if there was an error, ignore it
-                pass
         
         txt = "".join(self.__source)
         try:
@@ -252,16 +245,16 @@
             """
             return b.startswith(a) or a.startswith(b)
         
-        if self.__noFixCodes:
-            for noFixCode in [c.strip() for c in self.__noFixCodes]:
-                if mutualStartswith(code.lower(), noFixCode.lower()):
-                    return False
+        if (
+            self.__noFixCodes and
+            any(mutualStartswith(code.lower(), noFixCode.lower())
+                for noFixCode in [c.strip() for c in self.__noFixCodes])
+        ):
+            return False
 
         if self.__fixCodes:
-            for fixCode in [c.strip() for c in self.__fixCodes]:
-                if mutualStartswith(code.lower(), fixCode.lower()):
-                    return True
-            return False
+            return any(mutualStartswith(code.lower(), fixCode.lower())
+                       for fixCode in [c.strip() for c in self.__fixCodes])
 
         return True
     
@@ -378,7 +371,7 @@
         except (SyntaxError, tokenize.TokenError):
             return None
 
-        line = line - 1
+        line -= 1
         ls = None
         le = None
         for i in range(0, len(logical_start)):
@@ -401,13 +394,11 @@
         """
         sio = StringIO("".join(self.__source))
         indentWord = "    "     # default in case of failure
-        try:
+        with contextlib.suppress(SyntaxError, tokenize.TokenError):
             for token in tokenize.generate_tokens(sio.readline):
                 if token[0] == tokenize.INDENT:
                     indentWord = token[1]
                     break
-        except (SyntaxError, tokenize.TokenError):
-            pass
         return indentWord
     
     def __getIndent(self, line):
@@ -434,7 +425,7 @@
             self.__multiLineNumbers = set()
             self.__docLineNumbers = set()
             previousTokenType = ''
-            try:
+            with contextlib.suppress(SyntaxError, tokenize.TokenError):
                 for t in tokenize.generate_tokens(sio.readline):
                     tokenType = t[0]
                     startRow = t[2][0]
@@ -449,8 +440,6 @@
                                 range(startRow, 1 + endRow))
 
                     previousTokenType = tokenType
-            except (SyntaxError, tokenize.TokenError):
-                pass
         
         return self.__multiLineNumbers, self.__docLineNumbers
     
@@ -533,7 +522,7 @@
             message and an ID for a deferred fix
         @rtype tuple of (int, str, list or int, int)
         """
-        line = line - 1
+        line -= 1
         quotes = re.match(r"""\s*[ru]?('''|'|\")""",
                           self.__source[line]).group(1)
         left, right = self.__source[line].split(quotes, 1)
@@ -565,7 +554,7 @@
             message and an ID for a deferred fix
         @rtype tuple of (int, str, list or int, int)
         """
-        line = line - 1
+        line -= 1
         if code == "D112":
             insertChar = "r"
         else:
@@ -600,7 +589,7 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             if not self.__source[line].lstrip().startswith(
                     ('"""', 'r"""', 'u"""')):
                 # only correctly formatted docstrings will be fixed
@@ -643,7 +632,7 @@
             message and an ID for a deferred fix
         @rtype tuple of (int, str, list or int, int)
         """
-        line = line - 1
+        line -= 1
         newText = ""
         if (
             self.__source[line].rstrip().endswith(('"""', "'''")) and
@@ -694,7 +683,7 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             self.__source[line - 1] = ""
             # Blank line before function/method docstring removed.
             return (1, "FIXD141", [], 0)
@@ -724,7 +713,7 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             self.__source[line] = self.__eol + self.__source[line]
             # Blank line inserted before class docstring.
             return (1, "FIXD142", [], 0)
@@ -754,7 +743,7 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             self.__source[line] += self.__eol
             # Blank line inserted after class docstring.
             return (1, "FIXD143", [], 0)
@@ -784,7 +773,7 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             if not self.__source[line].rstrip().endswith("."):
                 # only correct summary lines can be fixed here
                 return (0, "", 0)
@@ -818,7 +807,7 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             self.__source[line] = self.__eol + self.__source[line]
             # Blank line inserted after last paragraph of docstring.
             return (1, "FIXD145", [], 0)
@@ -848,7 +837,7 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             indent = self.__getIndent(self.__source[line])
             source = self.__source[line].strip()
             if code == "D221":
@@ -902,7 +891,7 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             self.__source[line - 1] = ""
             if code == "D242":
                 # Blank line before class docstring removed.
@@ -937,7 +926,7 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             self.__source[line + 1] = ""
             if code == "D243":
                 # Blank line after class docstring removed.
@@ -972,7 +961,7 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             self.__source[line - 1] = ""
             # Blank line after last paragraph removed.
             return (1, "FIXD247", [], 0)
@@ -1079,7 +1068,7 @@
                 modified = self.__fixReindent(line, pos, logical)
                 if not modified:
                     # fall back to simple method
-                    line = line - 1
+                    line -= 1
                     text = self.__source[line]
                     indentation = self.__getIndent(text)
                     self.__source[line] = (
@@ -1301,7 +1290,7 @@
             message and an ID for a deferred fix
         @rtype tuple of (int, str, list or int, int)
         """
-        line = line - 1
+        line -= 1
         text = self.__source[line]
         
         if '"""' in text or "'''" in text or text.rstrip().endswith('\\'):
@@ -1333,7 +1322,7 @@
             message and an ID for a deferred fix
         @rtype tuple of (int, str, list or int, int)
         """
-        line = line - 1
+        line -= 1
         text = self.__source[line]
         
         if '"""' in text or "'''" in text or text.rstrip().endswith('\\'):
@@ -1363,7 +1352,7 @@
             message and an ID for a deferred fix
         @rtype tuple of (int, str, list or int, int)
         """
-        line = line - 1
+        line -= 1
         text = self.__source[line]
         
         if '"""' in text or "'''" in text or text.rstrip().endswith('\\'):
@@ -1408,8 +1397,8 @@
             message and an ID for a deferred fix
         @rtype tuple of (int, str, list or int, int)
         """
-        line = line - 1
-        pos = pos + 1
+        line -= 1
+        pos += 1
         self.__source[line] = (
             self.__source[line][:pos] +
             " " +
@@ -1436,17 +1425,18 @@
             message and an ID for a deferred fix
         @rtype tuple of (int, str, list or int, int)
         """
-        line = line - 1
+        line -= 1
         text = self.__source[line]
         
         # This is necessary since pycodestyle sometimes reports columns that
         # goes past the end of the physical line. This happens in cases like,
         # foo(bar\n=None)
         col = min(pos, len(text) - 1)
-        if text[col].strip():
-            newText = text
-        else:
-            newText = text[:col].rstrip() + text[col:].lstrip()
+        newText = (
+            text
+            if text[col].strip() else
+            text[:col].rstrip() + text[col:].lstrip()
+        )
         
         # There could be an escaped newline
         if newText.endswith(('=\\\n', '=\\\r\n', '=\\\r')):
@@ -1474,7 +1464,7 @@
             message and an ID for a deferred fix
         @rtype tuple of (int, str, list or int, int)
         """
-        line = line - 1
+        line -= 1
         text = self.__source[line]
         left = text[:pos].rstrip(' \t#')
         right = text[pos:].lstrip(' \t#')
@@ -1600,7 +1590,7 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             text = self.__source[line]
             if not text.lstrip().startswith("import"):
                 return (0, "", [], 0)
@@ -1650,7 +1640,7 @@
                 self.__multilineStringLines()
             )
             isDocString = line in docStringLines
-            line = line - 1
+            line -= 1
             text = self.__source[line]
             if line > 0:
                 prevText = self.__source[line - 1]
@@ -1725,9 +1715,9 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             text = self.__source[line]
-            pos = pos + 1
+            pos += 1
             
             newText = (
                 text[:pos] +
@@ -1765,7 +1755,7 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             text = self.__source[line]
             
             if text.rstrip().endswith("\\"):
@@ -1802,7 +1792,7 @@
             message and an ID for a deferred fix
         @rtype tuple of (int, str, list or int, int)
         """
-        line = line - 1
+        line -= 1
         text = self.__source[line]
         
         rightPos = pos + 2
@@ -1848,7 +1838,7 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             text = self.__source[line]
             if code == "N804":
                 arg = "cls"
@@ -1901,7 +1891,7 @@
         @rtype tuple of (int, str, list or int, int)
         """
         if apply:
-            line = line - 1
+            line -= 1
             text = self.__source[line]
             index = text.find("(") + 1
             left = text[:index]
@@ -1920,7 +1910,7 @@
                 self.__source[line] = newText
             else:
                 # they are on the next line
-                line = line + 1
+                line += 1
                 text = self.__source[line]
                 indent = self.__getIndent(text)
                 right = text.lstrip()
@@ -2039,7 +2029,7 @@
         return (1, "FIXW603", [], 0)
 
 
-class Reindenter(object):
+class Reindenter:
     """
     Class to reindent badly-indented code to uniformly use four-space
     indentation.
@@ -2237,7 +2227,7 @@
         return i
 
 
-class IndentationWrapper(object):
+class IndentationWrapper:
     """
     Class used by fixers dealing with indentation.
 
@@ -2421,9 +2411,8 @@
 
                 if token_type == tokenize.OP and text in ']})':
                     pass
-                elif visual_indent is True:
-                    if not indent[depth]:
-                        indent[depth] = start[1]
+                elif visual_indent is True and not indent[depth]:
+                    indent[depth] = start[1]
 
             # line altered: comments shouldn't define a visual indent
             if parens[row] and not indent[depth] and token_type not in (
@@ -2464,7 +2453,7 @@
         return valid_indents
 
 
-class LineShortener(object):
+class LineShortener:
     """
     Class used to shorten lines to a given maximum of characters.
     """
@@ -2884,10 +2873,12 @@
                 '[': ']',
                 '{': '}'}.get(lines[0][-1], None)
 
-            if len(lines) > 1:
-                if (badStartingSymbol and
-                        lines[1].lstrip().startswith(badStartingSymbol)):
-                    rank += 20
+            if (
+                len(lines) > 1 and
+                badStartingSymbol and
+                lines[1].lstrip().startswith(badStartingSymbol)
+            ):
+                rank += 20
 
             if re.match(r".*[+\-\*/] \($", lines[0]):
                 # "1 * (\n" is ugly as hell.

eric ide

mercurial