Applied some code simplifications suggested by the new Simplify checker.

Thu, 08 Apr 2021 18:27:47 +0200

author
Detlev Offenbach <detlev@die-offenbachs.de>
date
Thu, 08 Apr 2021 18:27:47 +0200
changeset 8205
4a0f1f896341
parent 8204
fd477cded1c1
child 8206
adf11836cfce

Applied some code simplifications suggested by the new Simplify checker.

eric6.epj file | annotate | diff | comparison | revisions
eric6/DebugClients/Python/DebugUtilities.py file | annotate | diff | comparison | revisions
eric6/DebugClients/Python/DebugVariables.py file | annotate | diff | comparison | revisions
eric6/E5Gui/E5Application.py file | annotate | diff | comparison | revisions
eric6/E5Gui/E5Led.py file | annotate | diff | comparison | revisions
eric6/E5Gui/E5MainWindow.py file | annotate | diff | comparison | revisions
eric6/E5Gui/E5TreeWidget.py file | annotate | diff | comparison | revisions
eric6/Graphics/ApplicationDiagramBuilder.py file | annotate | diff | comparison | revisions
eric6/Graphics/UMLDialog.py file | annotate | diff | comparison | revisions
eric6/HexEdit/HexEditWidget.py file | annotate | diff | comparison | revisions
eric6/MicroPython/EspDevices.py file | annotate | diff | comparison | revisions
eric6/PluginManager/PluginInstallDialog.py file | annotate | diff | comparison | revisions
eric6/PluginManager/PluginManager.py file | annotate | diff | comparison | revisions
eric6/Plugins/CheckerPlugins/CodeStyleChecker/AstUtilities.py file | annotate | diff | comparison | revisions
eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleChecker.py file | annotate | diff | comparison | revisions
eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleCheckerDialog.py file | annotate | diff | comparison | revisions
eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleCodeSelectionDialog.py file | annotate | diff | comparison | revisions
eric6/Plugins/CheckerPlugins/CodeStyleChecker/DocStyle/DocStyleChecker.py file | annotate | diff | comparison | revisions
eric6/Plugins/CheckerPlugins/CodeStyleChecker/Miscellaneous/MiscellaneousChecker.py file | annotate | diff | comparison | revisions
eric6/Plugins/CheckerPlugins/CodeStyleChecker/Naming/NamingStyleChecker.py file | annotate | diff | comparison | revisions
eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/generalHardcodedPassword.py file | annotate | diff | comparison | revisions
eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/SecurityUtils.py file | annotate | diff | comparison | revisions
eric6/Plugins/CheckerPlugins/CodeStyleChecker/Simplify/SimplifyNodeVisitor.py file | annotate | diff | comparison | revisions
eric6/Plugins/CheckerPlugins/SyntaxChecker/SyntaxCheck.py file | annotate | diff | comparison | revisions
eric6/Plugins/PluginWizardQFileDialog.py file | annotate | diff | comparison | revisions
eric6/Plugins/VcsPlugins/vcsGit/GitStatusMonitorThread.py file | annotate | diff | comparison | revisions
eric6/Plugins/VcsPlugins/vcsMercurial/HgBookmarksInOutDialog.py file | annotate | diff | comparison | revisions
eric6/Plugins/VcsPlugins/vcsMercurial/HgStatusMonitorThread.py file | annotate | diff | comparison | revisions
eric6/Plugins/VcsPlugins/vcsMercurial/QueuesExtension/HgQueuesNewPatchDialog.py file | annotate | diff | comparison | revisions
eric6/Plugins/VcsPlugins/vcsMercurial/QueuesExtension/queues.py file | annotate | diff | comparison | revisions
eric6/Plugins/VcsPlugins/vcsMercurial/hg.py file | annotate | diff | comparison | revisions
eric6/Plugins/VcsPlugins/vcsPySvn/subversion.py file | annotate | diff | comparison | revisions
eric6/Plugins/VcsPlugins/vcsSubversion/subversion.py file | annotate | diff | comparison | revisions
eric6/Plugins/ViewManagerPlugins/Listspace/Listspace.py file | annotate | diff | comparison | revisions
eric6/Plugins/ViewManagerPlugins/Tabview/Tabview.py file | annotate | diff | comparison | revisions
eric6/Preferences/ConfigurationDialog.py file | annotate | diff | comparison | revisions
eric6/Preferences/ConfigurationPages/NetworkPage.py file | annotate | diff | comparison | revisions
eric6/Preferences/ConfigurationPages/NotificationsPage.py file | annotate | diff | comparison | revisions
eric6/Preferences/ConfigurationPages/SecurityPage.py file | annotate | diff | comparison | revisions
eric6/Preferences/ConfigurationPages/WebBrowserAppearancePage.py file | annotate | diff | comparison | revisions
eric6/Preferences/ShortcutsDialog.py file | annotate | diff | comparison | revisions
eric6/Preferences/ViewProfileDialog.py file | annotate | diff | comparison | revisions
eric6/Preferences/__init__.py file | annotate | diff | comparison | revisions
eric6/Project/Project.py file | annotate | diff | comparison | revisions
eric6/Project/QuickFindFileDialog.py file | annotate | diff | comparison | revisions
eric6/QScintilla/DocstringGenerator/PyDocstringGenerator.py file | annotate | diff | comparison | revisions
eric6/QScintilla/Editor.py file | annotate | diff | comparison | revisions
eric6/QScintilla/Exporters/ExporterHTML.py file | annotate | diff | comparison | revisions
eric6/QScintilla/Exporters/ExporterPDF.py file | annotate | diff | comparison | revisions
eric6/QScintilla/Exporters/ExporterRTF.py file | annotate | diff | comparison | revisions
eric6/QScintilla/Exporters/ExporterTEX.py file | annotate | diff | comparison | revisions
eric6/Snapshot/SnapshotWaylandGrabber.py file | annotate | diff | comparison | revisions
eric6/Tools/TrayStarter.py file | annotate | diff | comparison | revisions
eric6/Tools/UIPreviewer.py file | annotate | diff | comparison | revisions
eric6/UI/Browser.py file | annotate | diff | comparison | revisions
eric6/UI/EmailDialog.py file | annotate | diff | comparison | revisions
eric6/Utilities/ClassBrowsers/__init__.py file | annotate | diff | comparison | revisions
eric6/Utilities/ClassBrowsers/idlclbr.py file | annotate | diff | comparison | revisions
eric6/Utilities/ClassBrowsers/pyclbr.py file | annotate | diff | comparison | revisions
eric6/Utilities/ClassBrowsers/rbclbr.py file | annotate | diff | comparison | revisions
eric6/Utilities/FtpUtilities.py file | annotate | diff | comparison | revisions
eric6/Utilities/MimeTypes.py file | annotate | diff | comparison | revisions
eric6/Utilities/ModuleParser.py file | annotate | diff | comparison | revisions
eric6/Utilities/__init__.py file | annotate | diff | comparison | revisions
eric6/Utilities/crypto/py3AES.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/AdBlock/AdBlockSearchTree.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/Bookmarks/BookmarksImporters/ChromeImporter.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/Bookmarks/BookmarksImporters/FirefoxImporter.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/Bookmarks/BookmarksImporters/HtmlImporter.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/Bookmarks/BookmarksImporters/IExplorerImporter.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/Bookmarks/BookmarksImporters/OperaImporter.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/Bookmarks/BookmarksImporters/SafariImporter.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/Bookmarks/BookmarksImporters/XbelImporter.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/Bookmarks/BookmarksModel.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/Download/DownloadItem.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/OpenSearch/OpenSearchReader.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/SafeBrowsing/SafeBrowsingAPIClient.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/Session/SessionManager.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/TabManager/TabManagerWidget.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/UrlBar/UrlBar.py file | annotate | diff | comparison | revisions
eric6/WebBrowser/WebBrowserTabBar.py file | annotate | diff | comparison | revisions
scripts/install.py file | annotate | diff | comparison | revisions
--- a/eric6.epj	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6.epj	Thu Apr 08 18:27:47 2021 +0200
@@ -47,7 +47,7 @@
         "CopyrightAuthor": "",
         "CopyrightMinFileSize": 0,
         "DocstringType": "eric",
-        "EnabledCheckerCategories": "C, D, E, M, N, W",
+        "EnabledCheckerCategories": "C, D, E, M, N, Y, W",
         "ExcludeFiles": "*/ThirdParty/*, */coverage/*, */Ui_*.py, */Examples/*, */*_rc.py,*/pycodestyle.py,*/pyflakes/checker.py,*/mccabe.py,*/eradicate.py,*/ast_unparse.py",
         "ExcludeMessages": "C101,E265,E266,E305,E402,M201,M301,M302,M303,M304,M305,M306,M307,M308,M311,M312,M313,M314,M315,M321,M701,M702,M811,M834,N802,N803,N807,N808,N821,W293,W504",
         "FixCodes": "",
--- a/eric6/DebugClients/Python/DebugUtilities.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/DebugClients/Python/DebugUtilities.py	Thu Apr 08 18:27:47 2021 +0200
@@ -444,14 +444,10 @@
                 buf = ''
                 continue
         
-        if state in (DEFAULT, ARG):
-            if ch == '"':
-                state = IN_DOUBLE_QUOTE
-            else:
-                state = ARG
-                buf += ch
+        if state not in (DEFAULT, ARG, IN_DOUBLE_QUOTE):
+            raise RuntimeError('Illegal condition')
         
-        elif state == IN_DOUBLE_QUOTE:
+        if state == IN_DOUBLE_QUOTE:
             if ch == '"':
                 if i + 1 < argsLen and args[i + 1] == '"':
                     # Undocumented feature in Windows:
@@ -468,7 +464,11 @@
                 buf += ch
         
         else:
-            raise RuntimeError('Illegal condition')
+            if ch == '"':
+                state = IN_DOUBLE_QUOTE
+            else:
+                state = ARG
+                buf += ch
     
     if len(buf) > 0 or state != DEFAULT:
         result.append(buf)
--- a/eric6/DebugClients/Python/DebugVariables.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/DebugClients/Python/DebugVariables.py	Thu Apr 08 18:27:47 2021 +0200
@@ -489,7 +489,7 @@
                 return getattr(var, attribute, None)
         
         expectedID = int(attribute.split(" (ID:")[-1][:-1])
-        for key in var.keys():
+        for key in var:
             if id(key) == expectedID:
                 return var.getlist(key)
         
--- a/eric6/E5Gui/E5Application.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/E5Gui/E5Application.py	Thu Apr 08 18:27:47 2021 +0200
@@ -63,10 +63,10 @@
         @rtype any
         @exception KeyError raised when the given name is not known
         """
-        if name in self.__objectRegistry:
-            return self.__objectRegistry[name]
-        else:
+        if name not in self.__objectRegistry:
             raise KeyError('Object "{0}" is not registered.'.format(name))
+        
+        return self.__objectRegistry[name]
     
     def registerPluginObject(self, name, objectRef, pluginType=None):
         """
@@ -106,11 +106,11 @@
         @rtype any
         @exception KeyError raised when the given name is not known
         """
-        if name in self.__pluginObjectRegistry:
-            return self.__pluginObjectRegistry[name][0]
-        else:
+        if name not in self.__pluginObjectRegistry:
             raise KeyError(
                 'Pluginobject "{0}" is not registered.'.format(name))
+        
+        return self.__pluginObjectRegistry[name][0]
     
     def getPluginObjects(self):
         """
@@ -135,11 +135,11 @@
         @rtype str
         @exception KeyError raised when the given name is not known
         """
-        if name in self.__pluginObjectRegistry:
-            return self.__pluginObjectRegistry[name][1]
-        else:
+        if name not in self.__pluginObjectRegistry:
             raise KeyError(
                 'Pluginobject "{0}" is not registered.'.format(name))
+        
+        return self.__pluginObjectRegistry[name][1]
     
     def usesDarkPalette(self):
         """
--- a/eric6/E5Gui/E5Led.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/E5Gui/E5Led.py	Thu Apr 08 18:27:47 2021 +0200
@@ -50,16 +50,18 @@
         """
         Protected slot handling the paint event.
         
-        @param evt paint event object (QPaintEvent)
+        @param evt paint event object
+        @type QPaintEvent
         @exception TypeError The E5Led has an unsupported shape type.
         """
+        if self.__shape not in (E5LedCircular, E5LedRectangular):
+            raise TypeError("Unsupported shape type for E5Led.")
+        
         if self.__shape == E5LedCircular:
             self.__paintRound()
         elif self.__shape == E5LedRectangular:
             self.__paintRectangular()
-        else:
-            raise TypeError("Unsupported shape type for E5Led.")
-        
+    
     def __getBestRoundSize(self):
         """
         Private method to calculate the width of the LED.
--- a/eric6/E5Gui/E5MainWindow.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/E5Gui/E5MainWindow.py	Thu Apr 08 18:27:47 2021 +0200
@@ -39,6 +39,7 @@
         # step 1: set the style
         style = None
         if styleName != "System" and styleName in QStyleFactory.keys():
+            # __IGNORE_WARNING_Y118__
             style = QStyleFactory.create(styleName)
         if style is None:
             style = QStyleFactory.create(self.defaultStyleName)
--- a/eric6/E5Gui/E5TreeWidget.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/E5Gui/E5TreeWidget.py	Thu Apr 08 18:27:47 2021 +0200
@@ -79,19 +79,20 @@
         @exception RuntimeError raised to indicate an illegal type for
             the parent
         """
+        if not isinstance(parent, (QTreeWidgetItem, str)):
+            raise RuntimeError("illegal type for parent")
+        
         if isinstance(parent, QTreeWidgetItem):
             if parent is None or parent.treeWidget() != self:
                 return False
             parentItem = parent
-        elif isinstance(parent, str):
+        else:
             lst = self.findItems(parent, Qt.MatchFlag.MatchExactly)
             if not lst:
                 return False
             parentItem = lst[0]
             if parentItem is None:
                 return False
-        else:
-            raise RuntimeError("illegal type for parent")
         
         self.__allTreeItems.append(item)
         parentItem.addChild(item)
@@ -108,19 +109,20 @@
         @exception RuntimeError raised to indicate an illegal type for
             the parent
         """
+        if not isinstance(parent, (QTreeWidgetItem, str)):
+            raise RuntimeError("illegal type for parent")
+        
         if isinstance(parent, QTreeWidgetItem):
             if parent is None or parent.treeWidget() != self:
                 return False
             parentItem = parent
-        elif isinstance(parent, str):
+        else:
             lst = self.findItems(parent, Qt.MatchFlag.MatchExactly)
             if not lst:
                 return False
             parentItem = lst[0]
             if parentItem is None:
                 return False
-        else:
-            raise RuntimeError("illegal type for parent")
         
         self.__allTreeItems.append(item)
         parentItem.insertChild(0, item)
--- a/eric6/Graphics/ApplicationDiagramBuilder.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Graphics/ApplicationDiagramBuilder.py	Thu Apr 08 18:27:47 2021 +0200
@@ -187,7 +187,7 @@
                 impPackage = '.'.join(imp.split('.')[:-1])
                 if (
                     impPackage not in packages[package][1] and
-                    not impPackage == package
+                    impPackage != package
                 ):
                     packages[package][1].append(impPackage)
                     
--- a/eric6/Graphics/UMLDialog.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Graphics/UMLDialog.py	Thu Apr 08 18:27:47 2021 +0200
@@ -163,6 +163,14 @@
         @return reference to the instantiated diagram builder
         @exception ValueError raised to indicate an illegal diagram type
         """
+        if diagramType not in (
+            UMLDialog.ClassDiagram, UMLDialog.PackageDiagram,
+            UMLDialog.ImportsDiagram, UMLDialog.ApplicationDiagram,
+            UMLDialog.NoDiagram
+        ):
+            raise ValueError(self.tr(
+                "Illegal diagram type '{0}' given.").format(diagramType))
+        
         if diagramType == UMLDialog.ClassDiagram:
             from .UMLClassDiagramBuilder import UMLClassDiagramBuilder
             return UMLClassDiagramBuilder(
@@ -179,11 +187,8 @@
             from .ApplicationDiagramBuilder import ApplicationDiagramBuilder
             return ApplicationDiagramBuilder(
                 self, self.umlView, self.__project, **kwargs)
-        elif diagramType == UMLDialog.NoDiagram:
+        else:
             return None
-        else:
-            raise ValueError(self.tr(
-                "Illegal diagram type '{0}' given.").format(diagramType))
     
     def __diagramTypeString(self):
         """
--- a/eric6/HexEdit/HexEditWidget.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/HexEdit/HexEditWidget.py	Thu Apr 08 18:27:47 2021 +0200
@@ -460,16 +460,17 @@
         @rtype bool
         @exception TypeError raised to indicate a wrong parameter type
         """
+        if not isinstance(dataOrDevice, (bytearray, QByteArray, QIODevice)):
+            raise TypeError(
+                "setData: parameter must be bytearray, "
+                "QByteArray or QIODevice")
+        
         if isinstance(dataOrDevice, (bytearray, QByteArray)):
             self.__data = bytearray(dataOrDevice)
             self.__bData.setData(self.__data)
             return self.__setData(self.__bData)
-        elif isinstance(dataOrDevice, QIODevice):
+        else:
             return self.__setData(dataOrDevice)
-        else:
-            raise TypeError(
-                "setData: parameter must be bytearray, "
-                "QByteArray or QIODevice")
     
     def __setData(self, ioDevice):
         """
--- a/eric6/MicroPython/EspDevices.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/MicroPython/EspDevices.py	Thu Apr 08 18:27:47 2021 +0200
@@ -202,13 +202,15 @@
         dlg = EspFirmwareSelectionDialog()
         if dlg.exec() == QDialog.DialogCode.Accepted:
             chip, firmware, baudRate, flashMode, _ = dlg.getData()
+            if chip not in ("esp8266", "esp32"):
+                raise ValueError(self.tr("Unsupported chip type '{0}'.")
+                                 .format(chip))
+            
             if chip == "esp8266":
                 flashAddress = "0x0000"
             elif chip == "esp32":
                 flashAddress = "0x1000"
-            else:
-                raise ValueError(self.tr("Unsupported chip type '{0}'.")
-                                 .format(chip))
+            
             flashArgs = [
                 "-u",
                 "-m", "esptool",
--- a/eric6/PluginManager/PluginInstallDialog.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/PluginManager/PluginInstallDialog.py	Thu Apr 08 18:27:47 2021 +0200
@@ -569,7 +569,7 @@
         @param pluginFileName name of the plugin file (string)
         @param packageName name of the plugin package (string)
         """
-        if packageName == "" or packageName == "None":
+        if packageName in ("", "None"):
             packageDir = None
         else:
             packageDir = os.path.join(destination, packageName)
--- a/eric6/PluginManager/PluginManager.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/PluginManager/PluginManager.py	Thu Apr 08 18:27:47 2021 +0200
@@ -300,7 +300,7 @@
         """
         for key in self.__priorityOrder:
             if key in self.pluginDirs:
-                if not self.pluginDirs[key] in sys.path:
+                if self.pluginDirs[key] not in sys.path:
                     sys.path.insert(2, self.pluginDirs[key])
                 UI.PixmapCache.addSearchPath(self.pluginDirs[key])
         
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/AstUtilities.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/AstUtilities.py	Thu Apr 08 18:27:47 2021 +0200
@@ -96,10 +96,10 @@
         @rtype any
         @exception TypeError raised to indicate an unsupported type
         """
-        if isinstance(node, ast.Constant):
-            return node.value
-        else:
+        if not isinstance(node, ast.Constant):
             raise TypeError("Illegal node type passed.")
+        
+        return node.value
 
 else:
     # functions for Python < 3.8
@@ -169,17 +169,18 @@
         @rtype one of str, bytes, int
         @exception TypeError raised to indicate an unsupported type
         """
+        if not isinstance(
+            node, (ast.Num, ast.Str, ast.Bytes, ast.NameConstant)
+        ):
+            raise TypeError("Illegal node type passed.")
+        
         if isinstance(node, ast.Num):
             return node.n
         
-        elif isinstance(node, ast.Str):
-            return node.s
-        
-        elif isinstance(node, ast.Bytes):
+        elif isinstance(node, (ast.Str, ast.Bytes)):
             return node.s
         
         elif isinstance(node, ast.NameConstant):
             return node.value
         
-        else:
-            raise TypeError("Illegal node type passed.")
+        return None
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleChecker.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleChecker.py	Thu Apr 08 18:27:47 2021 +0200
@@ -297,16 +297,18 @@
                 offset = offset[1:3]
         else:
             offset = (1, 0)
-        return ({
-            "file": filename,
-            "line": offset[0],
-            "offset": offset[1],
-            "code": "E901",
-            "args": [exc_type.__name__, exc.args[0]],
-        }, {
-            "E901": 1,
-        },
-        None)
+        return (
+            {
+                "file": filename,
+                "line": offset[0],
+                "offset": offset[1],
+                "code": "E901",
+                "args": [exc_type.__name__, exc.args[0]],
+            }, {
+                "E901": 1,
+            },
+            None
+        )
 
 
 def __checkCodeStyle(filename, source, args):
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleCheckerDialog.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleCheckerDialog.py	Thu Apr 08 18:27:47 2021 +0200
@@ -2051,6 +2051,7 @@
         
         for topRow in range(self.resultList.topLevelItemCount()):
             topItem = self.resultList.topLevelItem(topRow)
+            topItem.setExpanded(True)
             visibleChildren = topItem.childCount()
             for childIndex in range(topItem.childCount()):
                 childItem = topItem.child(childIndex)
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleCodeSelectionDialog.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleCodeSelectionDialog.py	Thu Apr 08 18:27:47 2021 +0200
@@ -45,7 +45,7 @@
         self.codeTable.headerItem().setText(self.codeTable.columnCount(), "")
         codeList = [code.strip() for code in codes.split(",") if code.strip()]
         if categories:
-            codeList = [code for code in codeList if not code[0] in categories]
+            codeList = [code for code in codeList if code[0] not in categories]
         
         if showFixCodes:
             from .CodeStyleFixer import FixableCodeStyleIssues
@@ -57,7 +57,7 @@
             if categories:
                 # filter by category
                 selectableCodes = [x for x in selectableCodes
-                                   if not x[0] in categories]
+                                   if x[0] not in categories]
         for code in sorted(selectableCodes):
             message = getTranslatedMessage(code, [], example=True)
             if message is None:
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/DocStyle/DocStyleChecker.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/DocStyle/DocStyleChecker.py	Thu Apr 08 18:27:47 2021 +0200
@@ -863,7 +863,7 @@
         summary, lineNumber = self.__getSummaryLine(docstringContext)
         if (
             functionName + "(" in summary.replace(" ", "") and
-            not functionName + "()" in summary.replace(" ", "")
+            functionName + "()" not in summary.replace(" ", "")
         ):
             # report only, if it is not an abbreviated form (i.e. function() )
             self.__error(docstringContext.start() + lineNumber, 0, "D133")
@@ -1034,7 +1034,7 @@
             if (
                 summary and
                 not summary.endswith(".") and
-                not summary.split(None, 1)[0].lower() == "constructor"
+                summary.split(None, 1)[0].lower() != "constructor"
             ):
                 self.__error(
                     docstringContext.start() + lineNumber +
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Miscellaneous/MiscellaneousChecker.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Miscellaneous/MiscellaneousChecker.py	Thu Apr 08 18:27:47 2021 +0200
@@ -33,8 +33,7 @@
     @ytype str
     """
     if isinstance(node, ast.Attribute):
-        for v in composeCallPath(node.value):
-            yield v
+        yield from composeCallPath(node.value)
         yield node.attr
     elif isinstance(node, ast.Name):
         yield node.id
@@ -452,7 +451,7 @@
         if isinstance(node, ast.Module) or not hasCode:
             return
 
-        if not (imports >= expectedImports):
+        if imports < expectedImports:
             if imports:
                 self.__error(node.lineno - 1, node.col_offset, "M701",
                              ", ".join(expectedImports), ", ".join(imports))
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Naming/NamingStyleChecker.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Naming/NamingStyleChecker.py	Thu Apr 08 18:27:47 2021 +0200
@@ -96,12 +96,10 @@
         @yield tuple giving line number, offset within line and error code
         @ytype tuple of (int, int, str)
         """
-        for error in self.__visitNode(node):
-            yield error
+        yield from self.__visitNode(node)
         self.__parents.append(node)
         for child in ast.iter_child_nodes(node):
-            for error in self.__visitTree(child):
-                yield error
+            yield from self.__visitTree(child)
         self.__parents.pop()
     
     def __visitNode(self, node):
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/generalHardcodedPassword.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/Checks/generalHardcodedPassword.py	Thu Apr 08 18:27:47 2021 +0200
@@ -153,7 +153,7 @@
     
     # go through all (param, value)s and look for candidates
     for key, val in zip(context.node.args.args, defs):
-        if isinstance(key, ast.Name) or isinstance(key, ast.arg):
+        if isinstance(key, (ast.Name, ast.arg)):
             if AstUtilities.isString(val) and RE_CANDIDATES.search(key.arg):
                 reportError(
                     context.node.lineno - 1,
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/SecurityUtils.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/SecurityUtils.py	Thu Apr 08 18:27:47 2021 +0200
@@ -156,10 +156,10 @@
     if isinstance(node, ast.Attribute):
         try:
             val = deepgetattr(node, 'value.id')
-            if val in aliases:
-                prefix = aliases[val]
-            else:
-                prefix = deepgetattr(node, 'value.id')
+            prefix = (
+                aliases[val] if val in aliases
+                else deepgetattr(node, 'value.id')
+            )
         except Exception:           # secok
             # We can't get the fully qualified name for an attr, just return
             # its base name.
@@ -195,9 +195,13 @@
     @return list containing the line number range
     @rtype list of int
     """
-    strip = {"body": None, "orelse": None,
-             "handlers": None, "finalbody": None}
-    for key in strip.keys():
+    strip = {
+        "body": None,
+        "orelse": None,
+        "handlers": None,
+        "finalbody": None
+    }
+    for key in strip:
         if hasattr(node, key):
             strip[key] = getattr(node, key)
             node.key = []
@@ -209,7 +213,7 @@
             lines_min = min(lines_min, n.lineno)
             lines_max = max(lines_max, n.lineno)
     
-    for key in strip.keys():
+    for key in strip:
         if strip[key] is not None:
             node.key = strip[key]
     
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Simplify/SimplifyNodeVisitor.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Simplify/SimplifyNodeVisitor.py	Thu Apr 08 18:27:47 2021 +0200
@@ -669,7 +669,7 @@
                     continue
                 
                 self.__error(node.lineno - 1, node.col_offset, "Y109",
-                             value, unparse(ast.List(elts=values)),
+                             value, unparse(ast.Tuple(elts=values)),
                              unparse(node))
     
     def __check110_111(self, node):
--- a/eric6/Plugins/CheckerPlugins/SyntaxChecker/SyntaxCheck.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/CheckerPlugins/SyntaxChecker/SyntaxCheck.py	Thu Apr 08 18:27:47 2021 +0200
@@ -207,15 +207,20 @@
     Function to compile one Python source file to Python bytecode
     and to perform a pyflakes check.
     
-    @param filename source filename (string)
-    @param codestring string containing the code to compile (string)
-    @param checkFlakes flag indicating to do a pyflakes check (boolean)
+    @param filename source filename
+    @type str
+    @param codestring string containing the code to compile
+    @type str
+    @param checkFlakes flag indicating to do a pyflakes check
+    @type bool
     @param ignoreStarImportWarnings flag indicating to
-        ignore 'star import' warnings (boolean)
+        ignore 'star import' warnings
+    @type bool
     @return dictionary with the keys 'error' and 'warnings' which
             hold a list containing details about the error/ warnings
             (file name, line number, column, codestring (only at syntax
             errors), the message, a list with arguments for the message)
+    @rtype dict
     """
     import builtins
     
@@ -296,9 +301,9 @@
         warnings = Checker(module, filename, withDoctest=True)
         warnings.messages.sort(key=lambda a: a.lineno)
         for warning in warnings.messages:
-            if ignoreStarImportWarnings and (
-                isinstance(warning, ImportStarUsed) or
-                isinstance(warning, ImportStarUsage)
+            if (
+                ignoreStarImportWarnings and
+                isinstance(warning, (ImportStarUsed, ImportStarUsage))
             ):
                 continue
             
--- a/eric6/Plugins/PluginWizardQFileDialog.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/PluginWizardQFileDialog.py	Thu Apr 08 18:27:47 2021 +0200
@@ -159,6 +159,9 @@
                 self.tr('No current editor'),
                 self.tr('Please open or create a file first.'))
         else:
+            if variant not in ("QFileDialog", "E5FileDialog"):
+                raise ValueError("Illegal dialog variant given")
+            
             if variant == "QFileDialog":
                 match = self.__pyqtRe.search(editor.text())
                 if match is None:
@@ -167,11 +170,9 @@
                 else:
                     # PyQt5/PyQt6
                     dialogVariant = int(match.group(1))
-            elif variant == "E5FileDialog":
+            else:
                 # E5FileDialog
                 dialogVariant = -1
-            else:
-                raise ValueError("Illegal dialog variant given")
             
             code, ok = self.__callForm(editor, dialogVariant)
             if ok:
--- a/eric6/Plugins/VcsPlugins/vcsGit/GitStatusMonitorThread.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/VcsPlugins/vcsGit/GitStatusMonitorThread.py	Thu Apr 08 18:27:47 2021 +0200
@@ -116,7 +116,7 @@
                         "{0} {1}".format(states[name], name))
             except KeyError:
                 self.statusList.append("{0} {1}".format(states[name], name))
-        for name in self.reportedStates.keys():
+        for name in self.reportedStates:
             if name not in states:
                 self.statusList.append("  {0}".format(name))
         self.reportedStates = states
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/HgBookmarksInOutDialog.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/VcsPlugins/vcsMercurial/HgBookmarksInOutDialog.py	Thu Apr 08 18:27:47 2021 +0200
@@ -83,12 +83,14 @@
         self.intercept = False
         self.activateWindow()
         
+        if self.mode not in (self.INCOMING, self.OUTGOING):
+            raise ValueError("Bad value for mode")
+        
         if self.mode == self.INCOMING:
             args = self.vcs.initCommand("incoming")
-        elif self.mode == self.OUTGOING:
+        else:
             args = self.vcs.initCommand("outgoing")
-        else:
-            raise ValueError("Bad value for mode")
+        
         args.append('--bookmarks')
         
         out, err = self.__hgClient.runcommand(args)
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/HgStatusMonitorThread.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/VcsPlugins/vcsMercurial/HgStatusMonitorThread.py	Thu Apr 08 18:27:47 2021 +0200
@@ -95,7 +95,7 @@
                         "{0} {1}".format(states[name], name))
             except KeyError:
                 self.statusList.append("{0} {1}".format(states[name], name))
-        for name in self.reportedStates.keys():
+        for name in self.reportedStates:
             if name not in states:
                 self.statusList.append("  {0}".format(name))
         self.reportedStates = states
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/QueuesExtension/HgQueuesNewPatchDialog.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/VcsPlugins/vcsMercurial/QueuesExtension/HgQueuesNewPatchDialog.py	Thu Apr 08 18:27:47 2021 +0200
@@ -33,15 +33,14 @@
         super(HgQueuesNewPatchDialog, self).__init__(parent)
         self.setupUi(self)
         
+        if mode not in (HgQueuesNewPatchDialog.REFRESH_MODE,
+                        HgQueuesNewPatchDialog.NEW_MODE):
+            raise ValueError("invalid value for mode")
+        
         self.__mode = mode
         if self.__mode == HgQueuesNewPatchDialog.REFRESH_MODE:
             self.nameLabel.hide()
             self.nameEdit.hide()
-        elif self.__mode == HgQueuesNewPatchDialog.NEW_MODE:
-            # nothing special here
-            pass
-        else:
-            raise ValueError("invalid value for mode")
         
         if message:
             self.messageEdit.setPlainText(message)
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/QueuesExtension/queues.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/VcsPlugins/vcsMercurial/QueuesExtension/queues.py	Thu Apr 08 18:27:47 2021 +0200
@@ -81,14 +81,17 @@
         """
         patchesList = []
         
+        if listType not in (Queues.APPLIED_LIST, Queues.UNAPPLIED_LIST,
+                            Queues.SERIES_LIST):
+            raise ValueError("illegal value for listType")
+        
         if listType == Queues.APPLIED_LIST:
             args = self.vcs.initCommand("qapplied")
         elif listType == Queues.UNAPPLIED_LIST:
             args = self.vcs.initCommand("qunapplied")
-        elif listType == Queues.SERIES_LIST:
+        else:
             args = self.vcs.initCommand("qseries")
-        else:
-            raise ValueError("illegal value for listType")
+        
         if withSummary:
             args.append("--summary")
         
@@ -277,6 +280,9 @@
         @return flag indicating that the project should be reread (boolean)
         @exception ValueError raised to indicate an invalid operation
         """
+        if operation not in (Queues.POP, Queues.PUSH, Queues.GOTO):
+            raise ValueError("illegal value for operation")
+        
         if operation == Queues.POP:
             args = self.vcs.initCommand("qpop")
             title = self.tr("Pop Patches")
@@ -285,12 +291,11 @@
             args = self.vcs.initCommand("qpush")
             title = self.tr("Push Patches")
             listType = Queues.UNAPPLIED_LIST
-        elif operation == Queues.GOTO:
+        else:
             args = self.vcs.initCommand("qgoto")
             title = self.tr("Go to Patch")
             listType = Queues.SERIES_LIST
-        else:
-            raise ValueError("illegal value for operation")
+        
         args.append("-v")
         if force:
             args.append("--force")
@@ -609,14 +614,16 @@
             Queues.QUEUE_PURGE, Queues.QUEUE_ACTIVATE)
         @exception ValueError raised to indicate an invalid operation
         """
+        if operation not in (Queues.QUEUE_PURGE, Queues.QUEUE_DELETE,
+                             Queues.QUEUE_ACTIVATE):
+            raise ValueError("illegal value for operation")
+        
         if operation == Queues.QUEUE_PURGE:
             title = self.tr("Purge Queue")
         elif operation == Queues.QUEUE_DELETE:
             title = self.tr("Delete Queue")
-        elif operation == Queues.QUEUE_ACTIVATE:
+        else:
             title = self.tr("Activate Queue")
-        else:
-            raise ValueError("illegal value for operation")
         
         from .HgQueuesQueueManagementDialog import (
             HgQueuesQueueManagementDialog
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/hg.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/VcsPlugins/vcsMercurial/hg.py	Thu Apr 08 18:27:47 2021 +0200
@@ -2424,15 +2424,17 @@
         if data:
             revs, phase, force = data
             
+            if phase not in ("p", "d", "s"):
+                raise ValueError("Invalid phase given.")
+            
             args = self.initCommand("phase")
             if phase == "p":
                 args.append("--public")
             elif phase == "d":
                 args.append("--draft")
-            elif phase == "s":
+            else:
                 args.append("--secret")
-            else:
-                raise ValueError("Invalid phase given.")
+            
             if force:
                 args.append("--force")
             for rev in revs:
--- a/eric6/Plugins/VcsPlugins/vcsPySvn/subversion.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/VcsPlugins/vcsPySvn/subversion.py	Thu Apr 08 18:27:47 2021 +0200
@@ -1463,7 +1463,7 @@
         dname = os.path.normcase(dname)
         
         found = False
-        for name in self.statusCache.keys():
+        for name in self.statusCache:
             if name in names:
                 found = True
                 names[name] = self.statusCache[name]
--- a/eric6/Plugins/VcsPlugins/vcsSubversion/subversion.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/VcsPlugins/vcsSubversion/subversion.py	Thu Apr 08 18:27:47 2021 +0200
@@ -1327,7 +1327,7 @@
         dname = os.path.normcase(dname)
         
         found = False
-        for name in self.statusCache.keys():
+        for name in self.statusCache:
             if name in names:
                 found = True
                 names[name] = self.statusCache[name]
--- a/eric6/Plugins/ViewManagerPlugins/Listspace/Listspace.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/ViewManagerPlugins/Listspace/Listspace.py	Thu Apr 08 18:27:47 2021 +0200
@@ -905,7 +905,7 @@
         """
         if (
             event.type() == QEvent.Type.MouseButtonPress and
-            not event.button() == Qt.MouseButton.RightButton
+            event.button() != Qt.MouseButton.RightButton
         ):
             switched = True
             if isinstance(watched, QStackedWidget):
--- a/eric6/Plugins/ViewManagerPlugins/Tabview/Tabview.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Plugins/ViewManagerPlugins/Tabview/Tabview.py	Thu Apr 08 18:27:47 2021 +0200
@@ -1344,7 +1344,7 @@
         """
         if (
             event.type() == QEvent.Type.MouseButtonPress and
-            not event.button() == Qt.MouseButton.RightButton
+            event.button() != Qt.MouseButton.RightButton
         ):
             switched = True
             self.currentTabWidget.showIndicator(False)
--- a/eric6/Preferences/ConfigurationDialog.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Preferences/ConfigurationDialog.py	Thu Apr 08 18:27:47 2021 +0200
@@ -75,11 +75,11 @@
     accepted = pyqtSignal()
     rejected = pyqtSignal()
     
+    # TODO: convert this to 'enum'
     DefaultMode = 0
-    HelpBrowserMode = 1
-    TrayStarterMode = 2
-    HexEditorMode = 3
-    WebBrowserMode = 4
+    TrayStarterMode = 1
+    HexEditorMode = 2
+    WebBrowserMode = 3
     
     def __init__(self, parent=None, fromEric=True, displayMode=DefaultMode,
                  expandedEntries=None):
@@ -90,13 +90,21 @@
         @param fromEric flag indicating a dialog generation from within the
             eric ide (boolean)
         @param displayMode mode of the configuration dialog
-            (DefaultMode, HelpBrowserMode, TrayStarterMode, HexEditorMode,
-             WebBrowserMode)
+            (DefaultMode, TrayStarterMode, HexEditorMode, WebBrowserMode)
         @exception RuntimeError raised to indicate an invalid dialog mode
         @param expandedEntries list of entries to be shown expanded
             (list of strings)
         """
         super(ConfigurationWidget, self).__init__(parent)
+        
+        if displayMode not in (
+            ConfigurationWidget.DefaultMode,
+            ConfigurationWidget.WebBrowserMode,
+            ConfigurationWidget.TrayStarterMode,
+            ConfigurationWidget.HexEditorMode,
+        ):
+            raise RuntimeError("Illegal mode value: {0}".format(displayMode))
+        
         self.fromEric = fromEric
         self.displayMode = displayMode
         self.__webEngine = getWebBrowserSupport() == "QtWebEngine"
@@ -428,9 +436,6 @@
                  "HexEditorPage", None, None],
             }
         
-        else:
-            raise RuntimeError("Illegal mode value: {0}".format(displayMode))
-        
         # generate the list entries
         self.__expandedEntries = []
         for key in sorted(self.configItems.keys()):
@@ -460,8 +465,7 @@
         self.buttonBox.accepted.connect(self.accept)
         self.buttonBox.rejected.connect(self.rejected)
         
-        if displayMode in [ConfigurationWidget.HelpBrowserMode,
-                           ConfigurationWidget.TrayStarterMode,
+        if displayMode in [ConfigurationWidget.TrayStarterMode,
                            ConfigurationWidget.HexEditorMode,
                            ConfigurationWidget.WebBrowserMode]:
             self.configListSearch.hide()
@@ -920,7 +924,6 @@
     masterPasswordChanged = pyqtSignal(str, str)
     
     DefaultMode = ConfigurationWidget.DefaultMode
-    HelpBrowserMode = ConfigurationWidget.HelpBrowserMode
     TrayStarterMode = ConfigurationWidget.TrayStarterMode
     HexEditorMode = ConfigurationWidget.HexEditorMode
     WebBrowserMode = ConfigurationWidget.WebBrowserMode
@@ -937,8 +940,7 @@
         @param fromEric flag indicating a dialog generation from within the
             eric ide (boolean)
         @param displayMode mode of the configuration dialog
-            (DefaultMode, HelpBrowserMode, TrayStarterMode, HexEditorMode,
-             WebBrowserMode)
+            (DefaultMode, TrayStarterMode, HexEditorMode, WebBrowserMode)
         @param expandedEntries list of entries to be shown expanded
             (list of strings)
         """
--- a/eric6/Preferences/ConfigurationPages/NetworkPage.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Preferences/ConfigurationPages/NetworkPage.py	Thu Apr 08 18:27:47 2021 +0200
@@ -111,13 +111,11 @@
         
         @param displayMode mode of the configuration dialog
             (ConfigurationWidget.DefaultMode,
-             ConfigurationWidget.HelpBrowserMode,
              ConfigurationWidget.WebBrowserMode)
         """
         from ..ConfigurationDialog import ConfigurationWidget
         if displayMode in (
             ConfigurationWidget.DefaultMode,
-            ConfigurationWidget.HelpBrowserMode,
             ConfigurationWidget.WebBrowserMode
         ):
             self.__displayMode = displayMode
--- a/eric6/Preferences/ConfigurationPages/NotificationsPage.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Preferences/ConfigurationPages/NotificationsPage.py	Thu Apr 08 18:27:47 2021 +0200
@@ -85,7 +85,7 @@
         Preferences.setUI("NotificationPosition", QPoint(
             self.xSpinBox.value(), self.ySpinBox.value()))
         
-        for key in self.__colors.keys():
+        for key in self.__colors:
             Preferences.setUI(key, self.__colors[key])
     
     @pyqtSlot(bool)
--- a/eric6/Preferences/ConfigurationPages/SecurityPage.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Preferences/ConfigurationPages/SecurityPage.py	Thu Apr 08 18:27:47 2021 +0200
@@ -54,13 +54,11 @@
         
         @param displayMode mode of the configuration dialog
             (ConfigurationWidget.DefaultMode,
-             ConfigurationWidget.HelpBrowserMode,
              ConfigurationWidget.WebBrowserMode)
         """
         from ..ConfigurationDialog import ConfigurationWidget
         if displayMode in (
             ConfigurationWidget.DefaultMode,
-            ConfigurationWidget.HelpBrowserMode,
             ConfigurationWidget.WebBrowserMode
         ):
             self.__displayMode = displayMode
--- a/eric6/Preferences/ConfigurationPages/WebBrowserAppearancePage.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Preferences/ConfigurationPages/WebBrowserAppearancePage.py	Thu Apr 08 18:27:47 2021 +0200
@@ -107,7 +107,6 @@
         
         @param displayMode mode of the configuration dialog
             (ConfigurationWidget.DefaultMode,
-             ConfigurationWidget.HelpBrowserMode,
              ConfigurationWidget.TrayStarterMode)
         """
         from ..ConfigurationDialog import ConfigurationWidget
--- a/eric6/Preferences/ShortcutsDialog.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Preferences/ShortcutsDialog.py	Thu Apr 08 18:27:47 2021 +0200
@@ -474,8 +474,8 @@
                     (self.actionButton.isChecked() and
                      rx.search(itm.text(0)) is not None) or
                     (self.shortcutButton.isChecked() and
-                     not txt.lower() in itm.text(1).lower() and
-                     not txt.lower() in itm.text(2).lower())
+                     txt.lower() not in itm.text(1).lower() and
+                     txt.lower() not in itm.text(2).lower())
                 ):
                     itm.setHidden(True)
                     childHiddenCount += 1
--- a/eric6/Preferences/ViewProfileDialog.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Preferences/ViewProfileDialog.py	Thu Apr 08 18:27:47 2021 +0200
@@ -32,14 +32,15 @@
         """
         super(ViewProfileDialog, self).__init__(parent)
         
+        if layout not in ("Toolboxes", "Sidebars"):
+            raise ValueError(
+                "Illegal layout given ({0}).".format(self.__layout))
+        
         self.__layout = layout
         if self.__layout == "Toolboxes":
             self.ui = Ui_ViewProfileToolboxesDialog()
-        elif self.__layout == "Sidebars":
+        else:
             self.ui = Ui_ViewProfileSidebarsDialog()
-        else:
-            raise ValueError(
-                "Illegal layout given ({0}).".format(self.__layout))
         self.ui.setupUi(self)
         
         if self.__layout in ["Toolboxes", "Sidebars"]:
--- a/eric6/Preferences/__init__.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Preferences/__init__.py	Thu Apr 08 18:27:47 2021 +0200
@@ -1877,7 +1877,7 @@
     """
     lang = prefClass.settings.value("UI/Language",
                                     prefClass.uiDefaults["Language"])
-    if lang == "None" or lang == "" or lang is None:
+    if lang in ("None", "", None):
         return None
     else:
         return lang
--- a/eric6/Project/Project.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Project/Project.py	Thu Apr 08 18:27:47 2021 +0200
@@ -2312,17 +2312,14 @@
         @return flag indicating, if the project contains the file (boolean)
         """
         fn = self.getRelativePath(fn)
-        if (
+        return (
             fn in self.pdata["SOURCES"] or
             fn in self.pdata["FORMS"] or
             fn in self.pdata["INTERFACES"] or
             fn in self.pdata["PROTOCOLS"] or
             fn in self.pdata["RESOURCES"] or
             fn in self.pdata["OTHERS"]
-        ):
-            return True
-        else:
-            return False
+        )
         
     def createNewProject(self):
         """
@@ -3562,24 +3559,20 @@
         """
         Public method to check, if a path starts with the project path.
         
-        @param path path to be checked (string)
+        @param path path to be checked
+        @type str
         @return flag indicating that the path starts with the project path
-            (boolean)
-        """
-        if self.ppath:
-            if path == self.ppath:
-                return True
-            elif (
-                Utilities.normcasepath(Utilities.toNativeSeparators(path))
-                .startswith(Utilities.normcasepath(
-                    Utilities.toNativeSeparators(self.ppath + "/")))
-            ):
-                return True
-            else:
-                return False
-        else:
-            return False
-        
+        @rtype bool
+        """
+        return (
+            bool(self.ppath) and
+            (path == self.ppath or
+             Utilities.normcasepath(Utilities.toNativeSeparators(path))
+             .startswith(Utilities.normcasepath(
+                         Utilities.toNativeSeparators(self.ppath + "/")))
+             )
+        )
+    
     def getProjectFile(self):
         """
         Public method to get the path of the project file.
@@ -5559,7 +5552,7 @@
         @param path name of the directory entry to create (string)
         @param zipFile open ZipFile object (zipfile.ZipFile)
         """
-        if path == "" or path == "/" or path == "\\":
+        if path in ("", "/", "\\"):
             return
         
         if not path.endswith("/") and not path.endswith("\\"):
--- a/eric6/Project/QuickFindFileDialog.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Project/QuickFindFileDialog.py	Thu Apr 08 18:27:47 2021 +0200
@@ -147,8 +147,7 @@
         for typ in ["SOURCES", "FORMS", "INTERFACES", "PROTOCOLS", "RESOURCES",
                     "TRANSLATIONS", "OTHERS"]:
             entries = self.project.pdata.get(typ)
-            for entry in entries[:]:
-                yield entry
+            yield from entries[:]
     
     def __sortedMatches(self, items, searchTerm):
         """
--- a/eric6/QScintilla/DocstringGenerator/PyDocstringGenerator.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/QScintilla/DocstringGenerator/PyDocstringGenerator.py	Thu Apr 08 18:27:47 2021 +0200
@@ -502,7 +502,7 @@
         
         for index, character in enumerate(text):
             if foundLeftQuote is False:
-                if character == "'" or character == '"':
+                if character in ("'", '"'):
                     foundLeftQuote = True
                     quote = character
                     leftPos = index
--- a/eric6/QScintilla/Editor.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/QScintilla/Editor.py	Thu Apr 08 18:27:47 2021 +0200
@@ -3693,7 +3693,7 @@
         ch = self.charAt(pos)
         
         # Don't go past the end of the previous line
-        if ch == '\n' or ch == '\r':
+        if ch in ('\n', '\r'):
             return "", pos
         
         return ch, pos
@@ -6383,7 +6383,7 @@
         seline = self.markerFindNext(0, 1 << self.syntaxerror)
         if seline >= 0:
             index = 0
-            for handle in self.syntaxerrors.keys():
+            for handle in self.syntaxerrors:
                 if self.markerLine(handle) == seline:
                     index = self.syntaxerrors[handle][0][1]
             self.setCursorPosition(seline, index)
@@ -6689,7 +6689,7 @@
             styleAnnotations = []
             
             # step 1: do warnings
-            for handle in self.warnings.keys():
+            for handle in self.warnings:
                 if self.markerLine(handle) == line:
                     for msg, warningType in self.warnings[handle]:
                         if warningType == self.WarningStyle:
@@ -6700,7 +6700,7 @@
                                 self.tr("Warning: {0}").format(msg))
             
             # step 2: do syntax errors
-            for handle in self.syntaxerrors.keys():
+            for handle in self.syntaxerrors:
                 if self.markerLine(handle) == line:
                     for msg, _ in self.syntaxerrors[handle]:
                         errorAnnotations.append(
--- a/eric6/QScintilla/Exporters/ExporterHTML.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/QScintilla/Exporters/ExporterHTML.py	Thu Apr 08 18:27:47 2021 +0200
@@ -27,7 +27,7 @@
 import Utilities
 
 
-class HTMLGenerator(object):
+class HTMLGenerator:
     """
     Class implementing an HTML generator for exporting source code.
     """
@@ -188,6 +188,7 @@
                                 html += '    font-size: {0:d}pt;\n'.format(
                                         QFontInfo(font).pointSize())
                             html += '}\n'
+                            # __IGNORE_WARNING_Y113__
                     else:
                         styleIsUsed[istyle] = False
                 istyle += 1
@@ -415,10 +416,7 @@
             return
         
         fn = self.editor.getFileName()
-        if fn:
-            extension = os.path.normcase(os.path.splitext(fn)[1][1:])
-        else:
-            extension = ""
+        extension = os.path.normcase(os.path.splitext(fn)[1][1:]) if fn else ""
         
         if (
             extension in Preferences.getEditor(
@@ -475,18 +473,18 @@
                 )
         
         if html:
-            try:
-                with E5OverrideCursor():
-                    with open(filename, "w", encoding="utf-8") as f:
-                        f.write(html)
-            except OSError as err:
-                E5MessageBox.critical(
-                    self.editor,
-                    self.tr("Export source"),
-                    self.tr(
-                        """<p>The source could not be exported to"""
-                        """ <b>{0}</b>.</p><p>Reason: {1}</p>""")
-                    .format(filename, str(err)))
+            with E5OverrideCursor(), open(filename, "w", encoding="utf-8"
+                                          ) as f:
+                try:
+                    f.write(html)
+                except OSError as err:
+                    E5MessageBox.critical(
+                        self.editor,
+                        self.tr("Export source"),
+                        self.tr(
+                            """<p>The source could not be exported to"""
+                            """ <b>{0}</b>.</p><p>Reason: {1}</p>""")
+                        .format(filename, str(err)))
         else:
             E5MessageBox.critical(
                 self.editor,
@@ -568,10 +566,12 @@
         text = self.editor.text()
         
         mermaidNeeded = False
-        if Preferences.getEditor("PreviewMarkdownMermaid"):
-            if MarkdownExtensions.MermaidRegexFullText.search(text):
-                extensions.append(MarkdownExtensions.MermaidExtension())
-                mermaidNeeded = True
+        if (
+            Preferences.getEditor("PreviewMarkdownMermaid") and
+            MarkdownExtensions.MermaidRegexFullText.search(text)
+        ):
+            extensions.append(MarkdownExtensions.MermaidExtension())
+            mermaidNeeded = True
         
         if Preferences.getEditor("PreviewMarkdownNLtoBR"):
             extensions.append('nl2br')
--- a/eric6/QScintilla/Exporters/ExporterPDF.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/QScintilla/Exporters/ExporterPDF.py	Thu Apr 08 18:27:47 2021 +0200
@@ -43,7 +43,7 @@
 }
 
 
-class PDFStyle(object):
+class PDFStyle:
     """
     Simple class to store the values of a PDF style.
     """
@@ -55,7 +55,7 @@
         self.font = 0
 
 
-class PDFObjectTracker(object):
+class PDFObjectTracker:
     """
     Class to conveniently handle the tracking of PDF objects so that the
     cross-reference table can be built (PDF1.4Ref(p39)).
@@ -118,7 +118,7 @@
         return xrefStart
 
 
-class PDFRender(object):
+class PDFRender:
     """
     Class to manage line and page rendering.
     
@@ -313,7 +313,7 @@
             self.styleCurrent = style_
         
         # escape these characters
-        if ch == ')' or ch == '(' or ch == '\\':
+        if ch in (')', '(', '\\'):
             self.segment += '\\'
         if ch != ' ':
             self.justWhiteSpace = False
@@ -419,7 +419,7 @@
         pdfColor = ""
         for component in [color.red(), color.green(), color.blue()]:
             c = (component * 1000 + 127) // 255
-            if c == 0 or c == 1000:
+            if c in (0, 1000):
                 pdfColor += "{0:d} ".format(c // 1000)
             else:
                 pdfColor += "0.{0:03d} ".format(c)
@@ -556,81 +556,79 @@
             else:
                 self.pr.fontSize = PDF_FONTSIZE_DEFAULT
         
-        try:
-            with E5OverrideCursor():
-                # save file in win ansi using cp1250
-                with open(filename, "w", encoding="cp1250",
-                          errors="backslashreplace") as f:
-                    
-                    # initialise PDF rendering
-                    ot = PDFObjectTracker(f)
-                    self.pr.oT = ot
-                    self.pr.startPDF()
+        with E5OverrideCursor(), open(filename, "w", encoding="cp1250",
+                                      errors="backslashreplace") as f:
+            # save file in win ansi using cp1250
+            try:
+                # initialise PDF rendering
+                ot = PDFObjectTracker(f)
+                self.pr.oT = ot
+                self.pr.startPDF()
+                
+                # do here all the writing
+                lengthDoc = self.editor.length()
+                
+                if lengthDoc == 0:
+                    self.pr.nextLine()  # enable zero length docs
+                else:
+                    pos = 0
+                    column = 0
+                    utf8 = self.editor.isUtf8()
+                    utf8Ch = b""
+                    utf8Len = 0
                     
-                    # do here all the writing
-                    lengthDoc = self.editor.length()
-                    
-                    if lengthDoc == 0:
-                        self.pr.nextLine()  # enable zero length docs
-                    else:
-                        pos = 0
-                        column = 0
-                        utf8 = self.editor.isUtf8()
-                        utf8Ch = b""
-                        utf8Len = 0
+                    while pos < lengthDoc:
+                        ch = self.editor.byteAt(pos)
+                        style = self.editor.styleAt(pos)
                         
-                        while pos < lengthDoc:
-                            ch = self.editor.byteAt(pos)
-                            style = self.editor.styleAt(pos)
-                            
-                            if ch == b'\t':
-                                # expand tabs
-                                ts = tabSize - (column % tabSize)
-                                column += ts
-                                self.pr.add(' ' * ts, style)
-                            elif ch == b'\r' or ch == b'\n':
-                                if (
-                                    ch == b'\r' and
-                                    self.editor.byteAt(pos + 1) == b'\n'
-                                ):
-                                    pos += 1
-                                # close and begin a newline...
-                                self.pr.nextLine()
-                                column = 0
+                        if ch == b'\t':
+                            # expand tabs
+                            ts = tabSize - (column % tabSize)
+                            column += ts
+                            self.pr.add(' ' * ts, style)
+                        elif ch in (b'\r', b'\n'):
+                            if (
+                                ch == b'\r' and
+                                self.editor.byteAt(pos + 1) == b'\n'
+                            ):
+                                pos += 1
+                            # close and begin a newline...
+                            self.pr.nextLine()
+                            column = 0
+                        else:
+                            # write the character normally...
+                            if ord(ch) > 127 and utf8:
+                                utf8Ch += ch
+                                if utf8Len == 0:
+                                    if (utf8Ch[0] & 0xF0) == 0xF0:
+                                        utf8Len = 4
+                                    elif (utf8Ch[0] & 0xE0) == 0xE0:
+                                        utf8Len = 3
+                                    elif (utf8Ch[0] & 0xC0) == 0xC0:
+                                        utf8Len = 2
+                                    column -= 1
+                                    # will be incremented again later
+                                elif len(utf8Ch) == utf8Len:
+                                    ch = utf8Ch.decode('utf8')
+                                    self.pr.add(ch, style)
+                                    utf8Ch = b""
+                                    utf8Len = 0
+                                else:
+                                    column -= 1
+                                    # will be incremented again later
                             else:
-                                # write the character normally...
-                                if ord(ch) > 127 and utf8:
-                                    utf8Ch += ch
-                                    if utf8Len == 0:
-                                        if (utf8Ch[0] & 0xF0) == 0xF0:
-                                            utf8Len = 4
-                                        elif (utf8Ch[0] & 0xE0) == 0xE0:
-                                            utf8Len = 3
-                                        elif (utf8Ch[0] & 0xC0) == 0xC0:
-                                            utf8Len = 2
-                                        column -= 1
-                                        # will be incremented again later
-                                    elif len(utf8Ch) == utf8Len:
-                                        ch = utf8Ch.decode('utf8')
-                                        self.pr.add(ch, style)
-                                        utf8Ch = b""
-                                        utf8Len = 0
-                                    else:
-                                        column -= 1
-                                        # will be incremented again later
-                                else:
-                                    self.pr.add(ch.decode(), style)
-                                column += 1
-                            
-                            pos += 1
-                    
-                    # write required stuff and close the PDF file
-                    self.pr.endPDF()
-        except OSError as err:
-            E5MessageBox.critical(
-                self.editor,
-                self.tr("Export source"),
-                self.tr(
-                    """<p>The source could not be exported to"""
-                    """ <b>{0}</b>.</p><p>Reason: {1}</p>""")
-                .format(filename, str(err)))
+                                self.pr.add(ch.decode(), style)
+                            column += 1
+                        
+                        pos += 1
+                
+                # write required stuff and close the PDF file
+                self.pr.endPDF()
+            except OSError as err:
+                E5MessageBox.critical(
+                    self.editor,
+                    self.tr("Export source"),
+                    self.tr(
+                        """<p>The source could not be exported to"""
+                        """ <b>{0}</b>.</p><p>Reason: {1}</p>""")
+                    .format(filename, str(err)))
--- a/eric6/QScintilla/Exporters/ExporterRTF.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/QScintilla/Exporters/ExporterRTF.py	Thu Apr 08 18:27:47 2021 +0200
@@ -124,101 +124,100 @@
         if tabSize == 0:
             tabSize = 4
         
-        try:
-            with E5OverrideCursor():
-                with open(filename, "w", encoding="utf-8") as f:
-                    styles, fontsize = self.__prepareStyles(f)
-                    
-                    lastStyle = (
-                        self.RTF_SETFONTFACE + "0" +
-                        self.RTF_SETFONTSIZE + "{0:d}".format(fontsize) +
-                        self.RTF_SETCOLOR + "0" +
-                        self.RTF_SETBACKGROUND + "1" +
-                        self.RTF_BOLD_OFF +
-                        self.RTF_ITALIC_OFF
-                    )
-                    
-                    lengthDoc = self.editor.length()
-                    prevCR = False
-                    column = 0
-                    pos = 0
-                    deltaStyle = ""
-                    styleCurrent = -1
-                    utf8 = self.editor.isUtf8()
-                    utf8Ch = b""
-                    utf8Len = 0
+        with E5OverrideCursor(), open(filename, "w", encoding="utf-8") as f:
+            try:
+                styles, fontsize = self.__prepareStyles(f)
+                
+                lastStyle = (
+                    self.RTF_SETFONTFACE + "0" +
+                    self.RTF_SETFONTSIZE + "{0:d}".format(fontsize) +
+                    self.RTF_SETCOLOR + "0" +
+                    self.RTF_SETBACKGROUND + "1" +
+                    self.RTF_BOLD_OFF +
+                    self.RTF_ITALIC_OFF
+                )
+                
+                lengthDoc = self.editor.length()
+                prevCR = False
+                column = 0
+                pos = 0
+                deltaStyle = ""
+                styleCurrent = -1
+                utf8 = self.editor.isUtf8()
+                utf8Ch = b""
+                utf8Len = 0
+                
+                while pos < lengthDoc:
+                    ch = self.editor.byteAt(pos)
+                    style = self.editor.styleAt(pos)
+                    if style != styleCurrent:
+                        deltaStyle = self.__GetRTFStyleChange(
+                            lastStyle, styles[style])
+                        if deltaStyle:
+                            f.write(deltaStyle)
+                        styleCurrent = style
+                        lastStyle = styles[style]
                     
-                    while pos < lengthDoc:
-                        ch = self.editor.byteAt(pos)
-                        style = self.editor.styleAt(pos)
-                        if style != styleCurrent:
-                            deltaStyle = self.__GetRTFStyleChange(
-                                lastStyle, styles[style])
-                            if deltaStyle:
-                                f.write(deltaStyle)
-                            styleCurrent = style
-                            lastStyle = styles[style]
-                        
-                        if ch == b'{':
-                            f.write('\\{')
-                        elif ch == b'}':
-                            f.write('\\}')
-                        elif ch == b'\\':
-                            f.write('\\\\')
-                        elif ch == b'\t':
-                            if tabs:
-                                f.write(self.RTF_TAB)
-                            else:
-                                ts = tabSize - (column % tabSize)
-                                f.write(' ' * ts)
-                                column += ts - 1
-                        elif ch == b'\n':
-                            if not prevCR:
-                                f.write(self.RTF_EOLN)
-                                column -= 1
-                        elif ch == b'\r':
+                    if ch == b'{':
+                        f.write('\\{')
+                    elif ch == b'}':
+                        f.write('\\}')
+                    elif ch == b'\\':
+                        f.write('\\\\')
+                    elif ch == b'\t':
+                        if tabs:
+                            f.write(self.RTF_TAB)
+                        else:
+                            ts = tabSize - (column % tabSize)
+                            f.write(' ' * ts)
+                            column += ts - 1
+                    elif ch == b'\n':
+                        if not prevCR:
                             f.write(self.RTF_EOLN)
                             column -= 1
+                    elif ch == b'\r':
+                        f.write(self.RTF_EOLN)
+                        column -= 1
+                    else:
+                        if ord(ch) > 0x7F and utf8:
+                            utf8Ch += ch
+                            if utf8Len == 0:
+                                if (utf8Ch[0] & 0xF0) == 0xF0:
+                                    utf8Len = 4
+                                elif (utf8Ch[0] & 0xE0) == 0xE0:
+                                    utf8Len = 3
+                                elif (utf8Ch[0] & 0xC0) == 0xC0:
+                                    utf8Len = 2
+                                column -= 1
+                                # will be incremented again later
+                            elif len(utf8Ch) == utf8Len:
+                                ch = utf8Ch.decode('utf8')
+                                if ord(ch) <= 0xff:
+                                    f.write("\\'{0:x}".format(ord(ch)))
+                                else:
+                                    f.write("\\u{0:d}\\'{1:x}".format(
+                                            ord(ch), ord(ch) & 0xFF))
+                                utf8Ch = b""
+                                utf8Len = 0
+                            else:
+                                column -= 1
+                                # will be incremented again later
                         else:
-                            if ord(ch) > 0x7F and utf8:
-                                utf8Ch += ch
-                                if utf8Len == 0:
-                                    if (utf8Ch[0] & 0xF0) == 0xF0:
-                                        utf8Len = 4
-                                    elif (utf8Ch[0] & 0xE0) == 0xE0:
-                                        utf8Len = 3
-                                    elif (utf8Ch[0] & 0xC0) == 0xC0:
-                                        utf8Len = 2
-                                    column -= 1
-                                    # will be incremented again later
-                                elif len(utf8Ch) == utf8Len:
-                                    ch = utf8Ch.decode('utf8')
-                                    if ord(ch) <= 0xff:
-                                        f.write("\\'{0:x}".format(ord(ch)))
-                                    else:
-                                        f.write("\\u{0:d}\\'{1:x}".format(
-                                                ord(ch), ord(ch) & 0xFF))
-                                    utf8Ch = b""
-                                    utf8Len = 0
-                                else:
-                                    column -= 1
-                                    # will be incremented again later
-                            else:
-                                f.write(ch.decode())
-                        
-                        column += 1
-                        prevCR = ch == b'\r'
-                        pos += 1
+                            f.write(ch.decode())
                     
-                    f.write(self.RTF_BODYCLOSE)
-        except OSError as err:
-            E5MessageBox.critical(
-                self.editor,
-                self.tr("Export source"),
-                self.tr(
-                    """<p>The source could not be exported to"""
-                    """ <b>{0}</b>.</p><p>Reason: {1}</p>""")
-                .format(filename, str(err)))
+                    column += 1
+                    prevCR = ch == b'\r'
+                    pos += 1
+                
+                f.write(self.RTF_BODYCLOSE)
+            except OSError as err:
+                E5MessageBox.critical(
+                    self.editor,
+                    self.tr("Export source"),
+                    self.tr(
+                        """<p>The source could not be exported to"""
+                        """ <b>{0}</b>.</p><p>Reason: {1}</p>""")
+                    .format(filename, str(err)))
     
     def __prepareStyles(self, f):
         """
--- a/eric6/QScintilla/Exporters/ExporterTEX.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/QScintilla/Exporters/ExporterTEX.py	Thu Apr 08 18:27:47 2021 +0200
@@ -161,146 +161,142 @@
                 styleIsUsed[index] = True
         styleIsUsed[QsciScintilla.STYLE_DEFAULT] = True
         
-        try:
-            with E5OverrideCursor():
-                with open(filename, "w", encoding="utf-8") as f:
-                    
-                    f.write("\\documentclass[a4paper]{article}\n")
-                    f.write("\\usepackage[a4paper,margin=1.5cm]{geometry}\n")
-                    f.write("\\usepackage[T1]{fontenc}\n")
-                    f.write("\\usepackage{color}\n")
-                    f.write("\\usepackage{alltt}\n")
-                    f.write("\\usepackage{times}\n")
-                    if self.editor.isUtf8():
-                        f.write("\\usepackage[utf8]{inputenc}\n")
-                    else:
-                        f.write("\\usepackage[latin1]{inputenc}\n")
-                    
-                    if lex:
-                        istyle = 0
-                        while istyle <= QsciScintilla.STYLE_MAX:
-                            if (
-                                (istyle <= QsciScintilla.STYLE_DEFAULT or
-                                 istyle > QsciScintilla.STYLE_LASTPREDEFINED
-                                 ) and styleIsUsed[istyle]
-                            ):
-                                if (
-                                    lex.description(istyle) or
-                                    istyle == QsciScintilla.STYLE_DEFAULT
-                                ):
-                                    font = lex.font(istyle)
-                                    colour = lex.color(istyle)
-                                    paper = lex.paper(istyle)
-                                    
-                                    self.__defineTexStyle(
-                                        font, colour, paper, f, istyle)
-                                    # get substyles
-                                    subs_start, subs_count = (
-                                        self.editor.getSubStyleRange(istyle)
-                                    )
-                                    for subs_idx in range(subs_count):
-                                        font = lex.font(subs_start + subs_idx)
-                                        colour = lex.color(
-                                            subs_start + subs_idx)
-                                        paper = lex.paper(
-                                            subs_start + subs_idx)
-                                        
-                                        self.__defineTexStyle(
-                                            font, colour, paper, f,
-                                            subs_idx - subs_start)
-                                    
-                            istyle += 1
-                    else:
-                        colour = self.editor.color()
-                        paper = self.editor.paper()
-                        font = Preferences.getEditorOtherFonts("DefaultFont")
-                        
-                        self.__defineTexStyle(font, colour, paper, f, 0)
-                        self.__defineTexStyle(font, colour, paper, f,
-                                              QsciScintilla.STYLE_DEFAULT)
-                    
-                    f.write("\\begin{document}\n\n")
-                    if titleFullPath:
-                        title = self.editor.getFileName()
-                    else:
-                        title = os.path.basename(self.editor.getFileName())
-                    f.write(
-                        "Source File: {0}\n\n\\noindent\n\\tiny{{\n"
-                        .format(title))
-                    
-                    styleCurrent = self.editor.styleAt(0)
-                    f.write("\\eric{0}{{"
-                            .format(self.__texStyle(styleCurrent)))
+        with E5OverrideCursor(), open(filename, "w", encoding="utf-8") as f:
+            try:
+                f.write("\\documentclass[a4paper]{article}\n")
+                f.write("\\usepackage[a4paper,margin=1.5cm]{geometry}\n")
+                f.write("\\usepackage[T1]{fontenc}\n")
+                f.write("\\usepackage{color}\n")
+                f.write("\\usepackage{alltt}\n")
+                f.write("\\usepackage{times}\n")
+                if self.editor.isUtf8():
+                    f.write("\\usepackage[utf8]{inputenc}\n")
+                else:
+                    f.write("\\usepackage[latin1]{inputenc}\n")
+                
+                if lex:
+                    istyle = 0
+                    while istyle <= QsciScintilla.STYLE_MAX:
+                        if (
+                            (istyle <= QsciScintilla.STYLE_DEFAULT or
+                             istyle > QsciScintilla.STYLE_LASTPREDEFINED) and
+                            styleIsUsed[istyle] and
+                            (lex.description(istyle) or
+                             istyle == QsciScintilla.STYLE_DEFAULT)
+                        ):
+                            font = lex.font(istyle)
+                            colour = lex.color(istyle)
+                            paper = lex.paper(istyle)
+                            
+                            self.__defineTexStyle(
+                                font, colour, paper, f, istyle)
+                            # get substyles
+                            subs_start, subs_count = (
+                                self.editor.getSubStyleRange(istyle)
+                            )
+                            for subs_idx in range(subs_count):
+                                font = lex.font(subs_start + subs_idx)
+                                colour = lex.color(
+                                    subs_start + subs_idx)
+                                paper = lex.paper(
+                                    subs_start + subs_idx)
+                                
+                                self.__defineTexStyle(
+                                    font, colour, paper, f,
+                                    subs_idx - subs_start)
+                                
+                        istyle += 1
+                else:
+                    colour = self.editor.color()
+                    paper = self.editor.paper()
+                    font = Preferences.getEditorOtherFonts("DefaultFont")
                     
-                    lineIdx = 0
-                    pos = 0
-                    utf8 = self.editor.isUtf8()
-                    utf8Ch = b""
-                    utf8Len = 0
+                    self.__defineTexStyle(font, colour, paper, f, 0)
+                    self.__defineTexStyle(font, colour, paper, f,
+                                          QsciScintilla.STYLE_DEFAULT)
+                
+                f.write("\\begin{document}\n\n")
+                if titleFullPath:
+                    title = self.editor.getFileName()
+                else:
+                    title = os.path.basename(self.editor.getFileName())
+                f.write(
+                    "Source File: {0}\n\n\\noindent\n\\tiny{{\n"
+                    .format(title))
+                
+                styleCurrent = self.editor.styleAt(0)
+                f.write("\\eric{0}{{"
+                        .format(self.__texStyle(styleCurrent)))
+                
+                lineIdx = 0
+                pos = 0
+                utf8 = self.editor.isUtf8()
+                utf8Ch = b""
+                utf8Len = 0
+                
+                while pos < lengthDoc:
+                    ch = self.editor.byteAt(pos)
+                    style = self.editor.styleAt(pos)
+                    if style != styleCurrent:
+                        # new style
+                        f.write(
+                            "}}\n\\eric{0}{{".format(
+                                self.__texStyle(style)))
+                        styleCurrent = style
                     
-                    while pos < lengthDoc:
-                        ch = self.editor.byteAt(pos)
-                        style = self.editor.styleAt(pos)
-                        if style != styleCurrent:
-                            # new style
-                            f.write(
-                                "}}\n\\eric{0}{{".format(
-                                    self.__texStyle(style)))
-                            styleCurrent = style
-                        
-                        if ch == b'\t':
-                            ts = tabSize - (lineIdx % tabSize)
-                            lineIdx += ts - 1
-                            f.write("\\hspace*{{{0:d}em}}".format(ts))
-                        elif ch == b'\\':
-                            f.write("{\\textbackslash}")
-                        elif ch in [b'>', b'<', b'@']:
-                            f.write("${0}$".format(ch[0]))
-                        elif ch in [b'{', b'}', b'^', b'_', b'&', b'$', b'#',
-                                    b'%', b'~']:
-                            f.write("\\{0}".format(ch[0]))
-                        elif ch in [b'\r', b'\n']:
-                            lineIdx = -1    # because incremented below
-                            if (
-                                ch == b'\r' and
-                                self.editor.byteAt(pos + 1) == b'\n'
-                            ):
-                                pos += 1    # skip the LF
-                            styleCurrent = self.editor.styleAt(pos + 1)
-                            f.write("}} \\\\\n\\eric{0}{{".format(
-                                    self.__texStyle(styleCurrent)))
-                        elif ch == b' ':
-                            if self.editor.byteAt(pos + 1) == b' ':
-                                f.write("{\\hspace*{1em}}")
-                            else:
-                                f.write(' ')
+                    if ch == b'\t':
+                        ts = tabSize - (lineIdx % tabSize)
+                        lineIdx += ts - 1
+                        f.write("\\hspace*{{{0:d}em}}".format(ts))
+                    elif ch == b'\\':
+                        f.write("{\\textbackslash}")
+                    elif ch in [b'>', b'<', b'@']:
+                        f.write("${0}$".format(ch[0]))
+                    elif ch in [b'{', b'}', b'^', b'_', b'&', b'$', b'#',
+                                b'%', b'~']:
+                        f.write("\\{0}".format(ch[0]))
+                    elif ch in [b'\r', b'\n']:
+                        lineIdx = -1    # because incremented below
+                        if (
+                            ch == b'\r' and
+                            self.editor.byteAt(pos + 1) == b'\n'
+                        ):
+                            pos += 1    # skip the LF
+                        styleCurrent = self.editor.styleAt(pos + 1)
+                        f.write("}} \\\\\n\\eric{0}{{".format(
+                                self.__texStyle(styleCurrent)))
+                    elif ch == b' ':
+                        if self.editor.byteAt(pos + 1) == b' ':
+                            f.write("{\\hspace*{1em}}")
                         else:
-                            if ord(ch) > 127 and utf8:
-                                utf8Ch += ch
-                                if utf8Len == 0:
-                                    if (utf8Ch[0] & 0xF0) == 0xF0:
-                                        utf8Len = 4
-                                    elif (utf8Ch[0] & 0xE0) == 0xE0:
-                                        utf8Len = 3
-                                    elif (utf8Ch[0] & 0xC0) == 0xC0:
-                                        utf8Len = 2
-                                elif len(utf8Ch) == utf8Len:
-                                    ch = utf8Ch.decode('utf8')
-                                    f.write(ch)
-                                    utf8Ch = b""
-                                    utf8Len = 0
-                            else:
-                                f.write(ch.decode())
-                        lineIdx += 1
-                        pos += 1
-                    
-                    # close last empty style macros and document too
-                    f.write("}\n} %end tiny\n\n\\end{document}\n")
-        except OSError as err:
-            E5MessageBox.critical(
-                self.editor,
-                self.tr("Export source"),
-                self.tr(
-                    """<p>The source could not be exported to"""
-                    """ <b>{0}</b>.</p><p>Reason: {1}</p>""")
-                .format(filename, str(err)))
+                            f.write(' ')
+                    else:
+                        if ord(ch) > 127 and utf8:
+                            utf8Ch += ch
+                            if utf8Len == 0:
+                                if (utf8Ch[0] & 0xF0) == 0xF0:
+                                    utf8Len = 4
+                                elif (utf8Ch[0] & 0xE0) == 0xE0:
+                                    utf8Len = 3
+                                elif (utf8Ch[0] & 0xC0) == 0xC0:
+                                    utf8Len = 2
+                            elif len(utf8Ch) == utf8Len:
+                                ch = utf8Ch.decode('utf8')
+                                f.write(ch)
+                                utf8Ch = b""
+                                utf8Len = 0
+                        else:
+                            f.write(ch.decode())
+                    lineIdx += 1
+                    pos += 1
+                
+                # close last empty style macros and document too
+                f.write("}\n} %end tiny\n\n\\end{document}\n")
+            except OSError as err:
+                E5MessageBox.critical(
+                    self.editor,
+                    self.tr("Export source"),
+                    self.tr(
+                        """<p>The source could not be exported to"""
+                        """ <b>{0}</b>.</p><p>Reason: {1}</p>""")
+                    .format(filename, str(err)))
--- a/eric6/Snapshot/SnapshotWaylandGrabber.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Snapshot/SnapshotWaylandGrabber.py	Thu Apr 08 18:27:47 2021 +0200
@@ -105,16 +105,20 @@
         
         @exception RuntimeError raised to indicate an unsupported grab mode
         """
+        if self.__mode not in (
+            SnapshotModes.Fullscreen, SnapshotModes.SelectedScreen,
+            SnapshotModes.SelectedWindow, SnapshotModes.Rectangle,
+        ):
+            raise RuntimeError("unsupported grab mode given")
+        
         if self.__mode == SnapshotModes.Fullscreen:
             self.__grabFullscreen()
         elif self.__mode == SnapshotModes.SelectedScreen:
             self.__grabSelectedScreen()
         elif self.__mode == SnapshotModes.SelectedWindow:
             self.__grabSelectedWindow()
-        elif self.__mode == SnapshotModes.Rectangle:
+        else:
             self.__grabRectangle()
-        else:
-            raise RuntimeError("unsupported grab mode given")
     
     def __grabFullscreen(self):
         """
--- a/eric6/Tools/TrayStarter.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Tools/TrayStarter.py	Thu Apr 08 18:27:47 2021 +0200
@@ -230,9 +230,9 @@
         @param reason reason code of the signal
             (QSystemTrayIcon.ActivationReason)
         """
-        if (
-            reason == QSystemTrayIcon.ActivationReason.Context or
-            reason == QSystemTrayIcon.ActivationReason.MiddleClick
+        if reason in (
+            QSystemTrayIcon.ActivationReason.Context,
+            QSystemTrayIcon.ActivationReason.MiddleClick
         ):
             self.__showContextMenu()
         elif reason == QSystemTrayIcon.ActivationReason.DoubleClick:
--- a/eric6/Tools/UIPreviewer.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Tools/UIPreviewer.py	Thu Apr 08 18:27:47 2021 +0200
@@ -337,7 +337,8 @@
         """
         Private slot to load a ui file.
         
-        @param fn name of the ui file to be laoded (string)
+        @param fn name of the ui file to be laoded
+        @type str
         """
         if self.mainWidget:
             self.mainWidget.close()
@@ -354,10 +355,7 @@
         if self.mainWidget:
             self.currentFile = fn
             self.__updateChildren(self.styleCombo.currentText())
-            if (
-                isinstance(self.mainWidget, QDialog) or
-                isinstance(self.mainWidget, QMainWindow)
-            ):
+            if isinstance(self.mainWidget, (QDialog, QMainWindow)):
                 self.mainWidget.show()
                 self.mainWidget.installEventFilter(self)
             else:
--- a/eric6/UI/Browser.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/UI/Browser.py	Thu Apr 08 18:27:47 2021 +0200
@@ -909,8 +909,8 @@
                         .format(fname))
                 else:
                     try:
-                        f = open(filepath, "w")
-                        f.close()
+                        with open(filepath, "w"):
+                            pass
                     except OSError as err:
                         E5MessageBox.critical(
                             self,
--- a/eric6/UI/EmailDialog.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/UI/EmailDialog.py	Thu Apr 08 18:27:47 2021 +0200
@@ -286,11 +286,14 @@
                         txt.encode("utf-8"), _subtype=subtype,
                         _charset="utf-8")
             elif maintype == 'image':
-                att = MIMEImage(open(fname, 'rb').read(), _subtype=subtype)
+                with open(fname, 'rb') as f:
+                    att = MIMEImage(f.read(), _subtype=subtype)
             elif maintype == 'audio':
-                att = MIMEAudio(open(fname, 'rb').read(), _subtype=subtype)
+                with open(fname, 'rb') as f:
+                    att = MIMEAudio(f.read(), _subtype=subtype)
             else:
-                att = MIMEApplication(open(fname, 'rb').read())
+                with open(fname, 'rb') as f:
+                    att = MIMEApplication(f.read())
             att.add_header('Content-Disposition', 'attachment', filename=name)
             msg.attach(att)
             
--- a/eric6/Utilities/ClassBrowsers/__init__.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Utilities/ClassBrowsers/__init__.py	Thu Apr 08 18:27:47 2021 +0200
@@ -121,6 +121,7 @@
             pathname = os.path.join(p, name)
             if os.path.exists(pathname):
                 return (open(pathname), pathname, (ext, 'r', RB_SOURCE))
+                # __IGNORE_WARNING_Y115__
         raise ImportError
     
     elif ext in __extensions["IDL"]:
@@ -128,6 +129,7 @@
             pathname = os.path.join(p, name)
             if os.path.exists(pathname):
                 return (open(pathname), pathname, (ext, 'r', IDL_SOURCE))
+                # __IGNORE_WARNING_Y115__
         raise ImportError
     
     elif ext in __extensions["ProtoBuf"]:
@@ -135,6 +137,7 @@
             pathname = os.path.join(p, name)
             if os.path.exists(pathname):
                 return (open(pathname), pathname, (ext, 'r', PROTO_SOURCE))
+                # __IGNORE_WARNING_Y115__
         raise ImportError
     
     elif ext in __extensions["JavaScript"]:
@@ -142,6 +145,7 @@
             pathname = os.path.join(p, name)
             if os.path.exists(pathname):
                 return (open(pathname), pathname, (ext, 'r', JS_SOURCE))
+                # __IGNORE_WARNING_Y115__
         raise ImportError
     
     elif ext == '.ptl':
@@ -149,6 +153,7 @@
             pathname = os.path.join(p, name)
             if os.path.exists(pathname):
                 return (open(pathname), pathname, (ext, 'r', PTL_SOURCE))
+                # __IGNORE_WARNING_Y115__
         raise ImportError
     
     elif (
@@ -160,6 +165,7 @@
             pathname = os.path.join(p, name)
             if os.path.exists(pathname):
                 return (open(pathname), pathname, (ext, 'r', PY_SOURCE))
+                # __IGNORE_WARNING_Y115__
     raise ImportError
     
     # standard Python module file
@@ -172,5 +178,6 @@
     if isinstance(spec.loader, importlib.machinery.SourceFileLoader):
         ext = os.path.splitext(spec.origin)[-1]
         return (open(spec.origin), spec.origin, (ext, 'r', PY_SOURCE))
+        # __IGNORE_WARNING_Y115__
     
     raise ImportError
--- a/eric6/Utilities/ClassBrowsers/idlclbr.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Utilities/ClassBrowsers/idlclbr.py	Thu Apr 08 18:27:47 2021 +0200
@@ -334,10 +334,7 @@
             if classstack:
                 # it's an interface/module method
                 cur_class = classstack[-1][0]
-                if (
-                    isinstance(cur_class, Interface) or
-                    isinstance(cur_class, Module)
-                ):
+                if isinstance(cur_class, (Interface, Module)):
                     # it's a method
                     f = Function(None, meth_name,
                                  file, lineno, meth_sig)
@@ -420,7 +417,7 @@
                 if (
                     classstack[index][0] is not None and
                     not isinstance(classstack[index][0], Function) and
-                    not classstack[index][1] >= indent
+                    classstack[index][1] < indent
                 ):
                     attributes = m.group("AttributeNames").split(',')
                     ro = m.group("AttributeReadonly")
--- a/eric6/Utilities/ClassBrowsers/pyclbr.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Utilities/ClassBrowsers/pyclbr.py	Thu Apr 08 18:27:47 2021 +0200
@@ -705,7 +705,7 @@
     if '__all__' in dictionary:
         # set visibility of all top level elements
         pubs = dictionary['__all__']
-        for key in dictionary.keys():
+        for key in dictionary:
             if key == '__all__' or key.startswith("@@"):
                 continue
             if key in pubs.identifiers:
--- a/eric6/Utilities/ClassBrowsers/rbclbr.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Utilities/ClassBrowsers/rbclbr.py	Thu Apr 08 18:27:47 2021 +0200
@@ -347,10 +347,7 @@
             if classstack:
                 # it's a class/module method
                 cur_class = classstack[-1][0]
-                if (
-                    isinstance(cur_class, Class) or
-                    isinstance(cur_class, Module)
-                ):
+                if isinstance(cur_class, (Class, Module)):
                     # it's a method
                     f = Function(None, meth_name,
                                  file, lineno, meth_sig)
@@ -426,7 +423,7 @@
                 cls = classstack[-1][0]
                 if class_name in cls.classes:
                     cur_class = cls.classes[class_name]
-                elif cls.name == class_name or class_name == "self":
+                elif class_name in (cls.name, "self"):
                     cur_class = cls
                 else:
                     cls._addclass(class_name, cur_class)
@@ -500,7 +497,7 @@
                     if (
                         classstack[index][0] is not None and
                         not isinstance(classstack[index][0], Function) and
-                        not classstack[index][1] >= indent
+                        classstack[index][1] < indent
                     ):
                         parent = classstack[index][0]
                         actype = (
@@ -531,7 +528,7 @@
                 if (
                     classstack[index][0] is not None and
                     not isinstance(classstack[index][0], Function) and
-                    not classstack[index][1] >= indent
+                    classstack[index][1] < indent
                 ):
                     attr = Attribute(
                         module, m.group("AttributeName"), file, lineno)
@@ -551,7 +548,7 @@
                 if (
                     classstack[index][0] is not None and
                     not isinstance(classstack[index][0], Function) and
-                    not classstack[index][1] >= indent
+                    classstack[index][1] < indent
                 ):
                     parent = classstack[index][0]
                     if m.group("AttrType") is None:
@@ -580,7 +577,7 @@
                             )
                             if access == "_accessor":
                                 attr.setPublic()
-                            elif access == "_reader" or access == "_writer":
+                            elif access in ("_reader", "_writer"):
                                 if attr.isPrivate():
                                     attr.setProtected()
                                 elif attr.isProtected():
--- a/eric6/Utilities/FtpUtilities.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Utilities/FtpUtilities.py	Thu Apr 08 18:27:47 2021 +0200
@@ -323,9 +323,9 @@
         try:
             return self.__parseLine(line)
         except FtpDirLineParserError:
-            if self.__modeSwitchAllowed:
-                self.__parseLine = self.__parseWindowsLine
-                self.__modeSwitchAllowed = False
-                return self.__parseLine(line)
-            else:
+            if not self.__modeSwitchAllowed:
                 raise
+            
+            self.__parseLine = self.__parseWindowsLine
+            self.__modeSwitchAllowed = False
+            return self.__parseLine(line)
--- a/eric6/Utilities/MimeTypes.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Utilities/MimeTypes.py	Thu Apr 08 18:27:47 2021 +0200
@@ -16,23 +16,26 @@
     """
     Function to test, if the given file is a text (i.e. editable) file.
     
-    @param filename name of the file to be checked (string)
-    @return flag indicating an editable file (boolean)
+    @param filename name of the file to be checked
+    @type str
+    @return flag indicating an editable file
+    @rtype bool
     """
     type_ = mimetypes.guess_type(filename)[0]
-    if (type_ is None or
+    return (
+        type_ is None or
         type_.split("/")[0] == "text" or
-            type_ in Preferences.getUI("TextMimeTypes")):
-        return True
-    else:
-        return False
+        type_ in Preferences.getUI("TextMimeTypes")
+    )
 
 
 def mimeType(filename):
     """
     Function to get the mime type of a file.
     
-    @param filename name of the file to be checked (string)
-    @return mime type of the file (string)
+    @param filename name of the file to be checked
+    @type str
+    @return mime type of the file
+    @rtype str
     """
     return mimetypes.guess_type(filename)[0]
--- a/eric6/Utilities/ModuleParser.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Utilities/ModuleParser.py	Thu Apr 08 18:27:47 2021 +0200
@@ -874,7 +874,8 @@
         Private method to scan the source text of a Python module and retrieve
         the relevant information.
         
-        @param src the source text to be scanned (string)
+        @param src the source text to be scanned
+        @type str
         """
         lineno, last_lineno_pos = 1, 0
         classstack = []  # stack of (class, indent) pairs
@@ -927,10 +928,7 @@
                         if cur_class is None:
                             continue
                         
-                        if (
-                            isinstance(cur_class, Class) or
-                            isinstance(cur_class, RbModule)
-                        ):
+                        if isinstance(cur_class, (Class, RbModule)):
                             # it's a class/module method
                             f = Function(None, meth_name,
                                          None, lineno, meth_sig)
@@ -1087,7 +1085,7 @@
                         if (
                             classstack[index][0] is not None and
                             not isinstance(classstack[index][0], Function) and
-                            not classstack[index][1] >= indent
+                            classstack[index][1] < indent
                         ):
                             parent = classstack[index][0]
                             actype = (
@@ -1119,7 +1117,7 @@
                     if (
                         classstack[index][0] is not None and
                         not isinstance(classstack[index][0], Function) and
-                        not classstack[index][1] >= indent
+                        classstack[index][1] < indent
                     ):
                         attrName = m.group("AttributeName")
                         attr = Attribute(
@@ -1149,7 +1147,7 @@
                     if (
                         classstack[index][0] is not None and
                         not isinstance(classstack[index][0], Function) and
-                        not classstack[index][1] >= indent
+                        classstack[index][1] < indent
                     ):
                         parent = classstack[index][0]
                         if m.group("AttrType") is None:
@@ -1183,10 +1181,7 @@
                                 )
                                 if access == "_accessor":
                                     attr.setPublic()
-                                elif (
-                                    access == "_reader" or
-                                    access == "_writer"
-                                ):
+                                elif access in ("_reader", "_writer"):
                                     if attr.isPrivate():
                                         attr.setProtected()
                                     elif attr.isProtected():
@@ -1662,13 +1657,16 @@
                     if ext == '.ptl':
                         # Quixote page template
                         return (open(pathname), pathname,
+                        # __IGNORE_WARNING_Y115__
                                 ('.ptl', 'r', PTL_SOURCE))
                     elif ext == '.rb':
                         # Ruby source file
                         return (open(pathname), pathname,
+                        # __IGNORE_WARNING_Y115__
                                 ('.rb', 'r', RB_SOURCE))
                     else:
                         return (open(pathname), pathname,
+                        # __IGNORE_WARNING_Y115__
                                 (ext, 'r', PY_SOURCE))
             raise ImportError
     
@@ -1682,6 +1680,7 @@
     if isinstance(spec.loader, importlib.machinery.SourceFileLoader):
         ext = os.path.splitext(spec.origin)[-1]
         return (open(spec.origin), spec.origin, (ext, 'r', PY_SOURCE))
+        # __IGNORE_WARNING_Y115__
     
     raise ImportError
 
--- a/eric6/Utilities/__init__.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Utilities/__init__.py	Thu Apr 08 18:27:47 2021 +0200
@@ -834,21 +834,21 @@
     """
     Function to check, if a path starts with a given start path.
     
-    @param path path to be checked (string)
-    @param start start path (string)
+    @param path path to be checked
+    @type str
+    @param start start path
+    @type str
     @return flag indicating that the path starts with the given start
-        path (boolean)
+        path
+    @rtype bool
     """
-    if start:
-        if path == start:
-            return True
-        elif normcasepath(path).startswith(
-                normcasepath(start + "/")):
-            return True
-        else:
-            return False
-    else:
-        return False
+    return (
+        bool(start) and
+        (
+            path == start or
+            normcasepath(path).startswith(normcasepath(start + "/"))
+        )
+    )
 
 
 def relativeUniversalPath(path, start):
--- a/eric6/Utilities/crypto/py3AES.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/Utilities/crypto/py3AES.py	Thu Apr 08 18:27:47 2021 +0200
@@ -507,6 +507,9 @@
         @return encrypted data (bytes)
         @exception ValueError key size is invalid
         """
+        if size not in self.KeySize.values():
+            raise ValueError("Wrong key size given ({0}).".format(size))
+        
         output = bytearray(16)
         # the number of rounds
         nbrRounds = 0
@@ -517,10 +520,8 @@
             nbrRounds = 10
         elif size == self.KeySize["SIZE_192"]:
             nbrRounds = 12
-        elif size == self.KeySize["SIZE_256"]:
+        else:
             nbrRounds = 14
-        else:
-            raise ValueError("Wrong key size given ({0}).".format(size))
 
         # the expanded keySize
         expandedKeySize = 16 * (nbrRounds + 1)
@@ -564,20 +565,22 @@
         @return decrypted data (bytes)
         @exception ValueError key size is invalid
         """
+        if size not in self.KeySize.values():
+            raise ValueError("Wrong key size given ({0}).".format(size))
+        
         output = bytearray(16)
         # the number of rounds
         nbrRounds = 0
         # the 128 bit block to decode
         block = bytearray(16)
         # set the number of rounds
+        
         if size == self.KeySize["SIZE_128"]:
             nbrRounds = 10
         elif size == self.KeySize["SIZE_192"]:
             nbrRounds = 12
-        elif size == self.KeySize["SIZE_256"]:
+        else:
             nbrRounds = 14
-        else:
-            raise ValueError("Wrong key size given ({0}).".format(size))
 
         # the expanded keySize
         expandedKeySize = 16 * (nbrRounds + 1)
--- a/eric6/WebBrowser/AdBlock/AdBlockSearchTree.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/AdBlock/AdBlockSearchTree.py	Thu Apr 08 18:27:47 2021 +0200
@@ -108,7 +108,7 @@
         if not node:
             return
         
-        for key in node.children.keys():
+        for key in node.children:
             self.__deleteNode(node.children[key])
         
         node.children = {}
--- a/eric6/WebBrowser/Bookmarks/BookmarksImporters/ChromeImporter.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/Bookmarks/BookmarksImporters/ChromeImporter.py	Thu Apr 08 18:27:47 2021 +0200
@@ -29,6 +29,10 @@
         (string)
     @exception ValueError raised to indicate an invalid browser ID
     """
+    if sourceId not in ("chrome", "chromium"):
+        raise ValueError(
+            "Unsupported browser ID given ({0}).".format(sourceId))
+    
     if sourceId == "chrome":
         if Globals.isWindowsPlatform():
             standardDir = os.path.expandvars(
@@ -53,7 +57,7 @@
                 """Please choose the file to begin importing bookmarks."""),
             standardDir,
         )
-    elif sourceId == "chromium":
+    else:
         if Globals.isWindowsPlatform():
             standardDir = os.path.expandvars(
                 "%USERPROFILE%\\AppData\\Local\\Google\\Chrome\\"
@@ -73,9 +77,6 @@
                 """Please choose the file to begin importing bookmarks."""),
             standardDir,
         )
-    else:
-        raise ValueError(
-            "Unsupported browser ID given ({0}).".format(sourceId))
 
 
 class ChromeImporter(BookmarksImporter):
--- a/eric6/WebBrowser/Bookmarks/BookmarksImporters/FirefoxImporter.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/Bookmarks/BookmarksImporters/FirefoxImporter.py	Thu Apr 08 18:27:47 2021 +0200
@@ -29,32 +29,32 @@
         (string)
     @exception ValueError raised to indicate an invalid browser ID
     """
-    if sourceId == "firefox":
-        if Globals.isWindowsPlatform():
-            standardDir = os.path.expandvars(
-                "%APPDATA%\\Mozilla\\Firefox\\Profiles")
-        elif Globals.isMacPlatform():
-            standardDir = os.path.expanduser(
-                "~/Library/Application Support/Firefox/Profiles")
-        else:
-            standardDir = os.path.expanduser("~/.mozilla/firefox")
-        return (
-            UI.PixmapCache.getPixmap("chrome"),
-            "Mozilla Firefox",
-            "places.sqlite",
-            QCoreApplication.translate(
-                "FirefoxImporter",
-                """Mozilla Firefox stores its bookmarks in the"""
-                """ <b>places.sqlite</b> SQLite database. This file is"""
-                """ usually located in"""),
-            QCoreApplication.translate(
-                "FirefoxImporter",
-                """Please choose the file to begin importing bookmarks."""),
-            standardDir,
-        )
-    else:
+    if sourceId != "firefox":
         raise ValueError(
             "Unsupported browser ID given ({0}).".format(sourceId))
+    
+    if Globals.isWindowsPlatform():
+        standardDir = os.path.expandvars(
+            "%APPDATA%\\Mozilla\\Firefox\\Profiles")
+    elif Globals.isMacPlatform():
+        standardDir = os.path.expanduser(
+            "~/Library/Application Support/Firefox/Profiles")
+    else:
+        standardDir = os.path.expanduser("~/.mozilla/firefox")
+    return (
+        UI.PixmapCache.getPixmap("chrome"),
+        "Mozilla Firefox",
+        "places.sqlite",
+        QCoreApplication.translate(
+            "FirefoxImporter",
+            """Mozilla Firefox stores its bookmarks in the"""
+            """ <b>places.sqlite</b> SQLite database. This file is"""
+            """ usually located in"""),
+        QCoreApplication.translate(
+            "FirefoxImporter",
+            """Please choose the file to begin importing bookmarks."""),
+        standardDir,
+    )
 
 
 class FirefoxImporter(BookmarksImporter):
--- a/eric6/WebBrowser/Bookmarks/BookmarksImporters/HtmlImporter.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/Bookmarks/BookmarksImporters/HtmlImporter.py	Thu Apr 08 18:27:47 2021 +0200
@@ -27,26 +27,26 @@
         (string)
     @exception ValueError raised to indicate an invalid browser ID
     """
-    if sourceId == "html":
-        return (
-            UI.PixmapCache.getPixmap("html"),
-            "HTML Netscape Bookmarks",
-            QCoreApplication.translate(
-                "HtmlImporter",
-                "HTML Netscape Bookmarks") + " (*.htm *.html)",
-            QCoreApplication.translate(
-                "HtmlImporter",
-                """You can import bookmarks from any browser that supports"""
-                """ HTML exporting. This file has usually the extension"""
-                """ .htm or .html."""),
-            QCoreApplication.translate(
-                "HtmlImporter",
-                """Please choose the file to begin importing bookmarks."""),
-            "",
-        )
-    else:
+    if sourceId != "html":
         raise ValueError(
             "Unsupported browser ID given ({0}).".format(sourceId))
+    
+    return (
+        UI.PixmapCache.getPixmap("html"),
+        "HTML Netscape Bookmarks",
+        QCoreApplication.translate(
+            "HtmlImporter",
+            "HTML Netscape Bookmarks") + " (*.htm *.html)",
+        QCoreApplication.translate(
+            "HtmlImporter",
+            """You can import bookmarks from any browser that supports"""
+            """ HTML exporting. This file has usually the extension"""
+            """ .htm or .html."""),
+        QCoreApplication.translate(
+            "HtmlImporter",
+            """Please choose the file to begin importing bookmarks."""),
+        "",
+    )
 
 
 class HtmlImporter(BookmarksImporter):
--- a/eric6/WebBrowser/Bookmarks/BookmarksImporters/IExplorerImporter.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/Bookmarks/BookmarksImporters/IExplorerImporter.py	Thu Apr 08 18:27:47 2021 +0200
@@ -28,29 +28,29 @@
         (string)
     @exception ValueError raised to indicate an invalid browser ID
     """
-    if sourceId == "ie":
-        if Globals.isWindowsPlatform():
-            standardDir = os.path.expandvars(
-                "%USERPROFILE%\\Favorites")
-        else:
-            standardDir = ""
-        return (
-            UI.PixmapCache.getPixmap("internet_explorer"),
-            "Internet Explorer",
-            "",
-            QCoreApplication.translate(
-                "IExplorerImporter",
-                """Internet Explorer stores its bookmarks in the"""
-                """ <b>Favorites</b> folder This folder is usually"""
-                """ located in"""),
-            QCoreApplication.translate(
-                "IExplorerImporter",
-                """Please choose the folder to begin importing bookmarks."""),
-            standardDir,
-        )
-    else:
+    if sourceId != "ie":
         raise ValueError(
             "Unsupported browser ID given ({0}).".format(sourceId))
+    
+    if Globals.isWindowsPlatform():
+        standardDir = os.path.expandvars(
+            "%USERPROFILE%\\Favorites")
+    else:
+        standardDir = ""
+    return (
+        UI.PixmapCache.getPixmap("internet_explorer"),
+        "Internet Explorer",
+        "",
+        QCoreApplication.translate(
+            "IExplorerImporter",
+            """Internet Explorer stores its bookmarks in the"""
+            """ <b>Favorites</b> folder This folder is usually"""
+            """ located in"""),
+        QCoreApplication.translate(
+            "IExplorerImporter",
+            """Please choose the folder to begin importing bookmarks."""),
+        standardDir,
+    )
 
 
 class IExplorerImporter(BookmarksImporter):
--- a/eric6/WebBrowser/Bookmarks/BookmarksImporters/OperaImporter.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/Bookmarks/BookmarksImporters/OperaImporter.py	Thu Apr 08 18:27:47 2021 +0200
@@ -28,30 +28,30 @@
         (string)
     @exception ValueError raised to indicate an invalid browser ID
     """
-    if sourceId == "opera":
-        if Globals.isWindowsPlatform():
-            standardDir = os.path.expandvars("%APPDATA%\\Opera\\Opera")
-        elif Globals.isMacPlatform():
-            standardDir = os.path.expanduser(
-                "~/Library/Opera")
-        else:
-            standardDir = os.path.expanduser("~/.opera")
-        return (
-            UI.PixmapCache.getPixmap("opera"),
-            "Opera",
-            "bookmarks.adr",
-            QCoreApplication.translate(
-                "OperaImporter",
-                """Opera stores its bookmarks in the <b>bookmarks.adr</b> """
-                """text file. This file is usually located in"""),
-            QCoreApplication.translate(
-                "OperaImporter",
-                """Please choose the file to begin importing bookmarks."""),
-            standardDir,
-        )
-    else:
+    if sourceId != "opera":
         raise ValueError(
             "Unsupported browser ID given ({0}).".format(sourceId))
+    
+    if Globals.isWindowsPlatform():
+        standardDir = os.path.expandvars("%APPDATA%\\Opera\\Opera")
+    elif Globals.isMacPlatform():
+        standardDir = os.path.expanduser(
+            "~/Library/Opera")
+    else:
+        standardDir = os.path.expanduser("~/.opera")
+    return (
+        UI.PixmapCache.getPixmap("opera"),
+        "Opera",
+        "bookmarks.adr",
+        QCoreApplication.translate(
+            "OperaImporter",
+            """Opera stores its bookmarks in the <b>bookmarks.adr</b> """
+            """text file. This file is usually located in"""),
+        QCoreApplication.translate(
+            "OperaImporter",
+            """Please choose the file to begin importing bookmarks."""),
+        standardDir,
+    )
 
 
 class OperaImporter(BookmarksImporter):
--- a/eric6/WebBrowser/Bookmarks/BookmarksImporters/SafariImporter.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/Bookmarks/BookmarksImporters/SafariImporter.py	Thu Apr 08 18:27:47 2021 +0200
@@ -29,31 +29,31 @@
         (string)
     @exception ValueError raised to indicate an invalid browser ID
     """
-    if sourceId == "safari":
-        if Globals.isWindowsPlatform():
-            standardDir = os.path.expandvars(
-                "%APPDATA%\\Apple Computer\\Safari")
-        elif Globals.isMacPlatform():
-            standardDir = os.path.expanduser("~/Library/Safari")
-        else:
-            standardDir = ""
-        return (
-            UI.PixmapCache.getPixmap("safari"),
-            "Apple Safari",
-            "Bookmarks.plist",
-            QCoreApplication.translate(
-                "SafariImporter",
-                """Apple Safari stores its bookmarks in the"""
-                """ <b>Bookmarks.plist</b> file. This file is usually"""
-                """ located in"""),
-            QCoreApplication.translate(
-                "SafariImporter",
-                """Please choose the file to begin importing bookmarks."""),
-            standardDir,
-        )
-    else:
+    if sourceId != "safari":
         raise ValueError(
             "Unsupported browser ID given ({0}).".format(sourceId))
+    
+    if Globals.isWindowsPlatform():
+        standardDir = os.path.expandvars(
+            "%APPDATA%\\Apple Computer\\Safari")
+    elif Globals.isMacPlatform():
+        standardDir = os.path.expanduser("~/Library/Safari")
+    else:
+        standardDir = ""
+    return (
+        UI.PixmapCache.getPixmap("safari"),
+        "Apple Safari",
+        "Bookmarks.plist",
+        QCoreApplication.translate(
+            "SafariImporter",
+            """Apple Safari stores its bookmarks in the"""
+            """ <b>Bookmarks.plist</b> file. This file is usually"""
+            """ located in"""),
+        QCoreApplication.translate(
+            "SafariImporter",
+            """Please choose the file to begin importing bookmarks."""),
+        standardDir,
+    )
 
 
 class SafariImporter(BookmarksImporter):
--- a/eric6/WebBrowser/Bookmarks/BookmarksImporters/XbelImporter.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/Bookmarks/BookmarksImporters/XbelImporter.py	Thu Apr 08 18:27:47 2021 +0200
@@ -27,6 +27,10 @@
         (string)
     @exception ValueError raised to indicate an invalid browser ID
     """
+    if sourceId not in ("e5browser", "konqueror", "xbel"):
+        raise ValueError(
+            "Unsupported browser ID given ({0}).".format(sourceId))
+    
     if sourceId == "e5browser":
         from ..BookmarksManager import BookmarksManager
         bookmarksFile = BookmarksManager.getFileName()
@@ -65,7 +69,7 @@
                 """Please choose the file to begin importing bookmarks."""),
             standardDir,
         )
-    elif sourceId == "xbel":
+    else:
         return (
             UI.PixmapCache.getPixmap("xbel"),
             "XBEL Bookmarks",
@@ -81,9 +85,6 @@
                 """Please choose the file to begin importing bookmarks."""),
             "",
         )
-    else:
-        raise ValueError(
-            "Unsupported browser ID given ({0}).".format(sourceId))
 
 
 class XbelImporter(BookmarksImporter):
--- a/eric6/WebBrowser/Bookmarks/BookmarksModel.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/Bookmarks/BookmarksModel.py	Thu Apr 08 18:27:47 2021 +0200
@@ -127,9 +127,9 @@
         bookmarkNode = self.node(parent)
         children = bookmarkNode.children()[row:(row + count)]
         for node in children:
-            if (
-                node == self.__bookmarksManager.menu() or
-                node == self.__bookmarksManager.toolbar()
+            if node in (
+                self.__bookmarksManager.menu(),
+                self.__bookmarksManager.toolbar()
             ):
                 continue
             self.__bookmarksManager.removeBookmark(node)
@@ -201,13 +201,15 @@
         elif role == BookmarksModel.SeparatorRole:
             return bookmarkNode.type() == BookmarkNode.Separator
         
-        elif role == Qt.ItemDataRole.DecorationRole:
-            if index.column() == 0:
-                if bookmarkNode.type() == BookmarkNode.Folder:
-                    return UI.PixmapCache.getIcon("dirOpen")
-                import WebBrowser.WebBrowserWindow
-                return WebBrowser.WebBrowserWindow.WebBrowserWindow.icon(
-                    QUrl(bookmarkNode.url))
+        elif (
+            role == Qt.ItemDataRole.DecorationRole and
+            index.column() == 0
+        ):
+            if bookmarkNode.type() == BookmarkNode.Folder:
+                return UI.PixmapCache.getIcon("dirOpen")
+            import WebBrowser.WebBrowserWindow
+            return WebBrowser.WebBrowserWindow.WebBrowserWindow.icon(
+                QUrl(bookmarkNode.url))
         
         return None
     
@@ -282,10 +284,7 @@
             return QModelIndex()
         
         itemNode = self.node(index)
-        if itemNode is None:
-            parentNode = None
-        else:
-            parentNode = itemNode.parent()
+        parentNode = itemNode.parent() if itemNode else None
         
         if (
             parentNode is None or
@@ -332,9 +331,9 @@
         if self.hasChildren(index):
             flags |= Qt.ItemFlag.ItemIsDropEnabled
         
-        if (
-            node == self.__bookmarksManager.menu() or
-            node == self.__bookmarksManager.toolbar()
+        if node in (
+            self.__bookmarksManager.menu(),
+            self.__bookmarksManager.toolbar()
         ):
             return flags
         
--- a/eric6/WebBrowser/Download/DownloadItem.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/Download/DownloadItem.py	Thu Apr 08 18:27:47 2021 +0200
@@ -447,7 +447,7 @@
                 remaining
             )
         else:
-            if self.__bytesReceived == bytesTotal or bytesTotal == -1:
+            if bytesTotal in (self.__bytesReceived, -1):
                 info = self.tr(
                     "{0} downloaded"
                 ).format(dataString(self.__bytesReceived))
--- a/eric6/WebBrowser/OpenSearch/OpenSearchReader.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/OpenSearch/OpenSearchReader.py	Thu Apr 08 18:27:47 2021 +0200
@@ -75,8 +75,7 @@
                 
                 if (
                     (not type_ or
-                     type_ == "text/html" or
-                     type_ == "application/xhtml+xml") and
+                     type_ in ("text/html", "application/xhtml+xml")) and
                     engine.searchUrlTemplate()
                 ):
                     continue
@@ -112,8 +111,7 @@
                     engine.setSuggestionsMethod(method)
                 elif (
                     not type_ or
-                    type_ == "text/html" or
-                    type_ == "application/xhtml+xml"
+                    type_ in ("text/html", "application/xhtml+xml")
                 ):
                     engine.setSearchUrlTemplate(url)
                     engine.setSearchParameters(parameters)
--- a/eric6/WebBrowser/SafeBrowsing/SafeBrowsingAPIClient.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/SafeBrowsing/SafeBrowsingAPIClient.py	Thu Apr 08 18:27:47 2021 +0200
@@ -561,15 +561,16 @@
         """
         platform = platform.lower()
         
+        if platform not in ("linux", "windows", "macos"):
+            raise ValueError("Unsupported platform")
+        
         platformTypes = ["ANY_PLATFORM", "ALL_PLATFORMS"]
         if platform == "linux":
             platformTypes.append("LINUX")
         elif platform == "windows":
             platformTypes.append("WINDOWS")
-        elif platform == "macos":
+        else:
             platformTypes.append("OSX")
-        else:
-            raise ValueError("Unsupported platform")
         
         return platformTypes
     
--- a/eric6/WebBrowser/Session/SessionManager.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/Session/SessionManager.py	Thu Apr 08 18:27:47 2021 +0200
@@ -27,7 +27,7 @@
 import Preferences
 
 
-class SessionMetaData(object):
+class SessionMetaData:
     """
     Class implementing a data structure to store meta data for a session.
     """
@@ -417,8 +417,10 @@
                 if win is not window:
                     win.forceClose()
             
-            if not ((flags & SessionManager.ReplaceSession) ==
-                    SessionManager.ReplaceSession):
+            if (
+                (flags & SessionManager.ReplaceSession) !=
+                SessionManager.ReplaceSession
+            ):
                 self.__lastActiveSession = (
                     QFileInfo(sessionFilePath).canonicalFilePath()
                 )
--- a/eric6/WebBrowser/TabManager/TabManagerWidget.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/TabManager/TabManagerWidget.py	Thu Apr 08 18:27:47 2021 +0200
@@ -136,7 +136,7 @@
             for browser in browsersDict[mainWin]:
                 if (
                     not browser.url().isEmpty() and
-                    not browser.url().scheme() == "eric"
+                    browser.url().scheme() != "eric"
                 ):
                     bookmark = BookmarkNode(BookmarkNode.Bookmark)
                     bookmark.url = bytes(browser.url().toEncoded()).decode()
@@ -310,9 +310,7 @@
         
         self.__isRefreshing = True
         
-        winCount = 0
-        for mainWin in windows:
-            winCount += 1
+        for winCount, mainWin in enumerate(windows, start=1):
             winItem = self.__createEmptyItem()
             winItem.setText(0, self.tr("Window {0}").format(winCount))
             winItem.setToolTip(0, self.tr("Double click to switch"))
--- a/eric6/WebBrowser/UrlBar/UrlBar.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/UrlBar/UrlBar.py	Thu Apr 08 18:27:47 2021 +0200
@@ -261,7 +261,7 @@
                     backgroundColor = Preferences.getWebBrowser(
                         "SecureUrlColor")
             
-            if progress == 0 or progress == 100:
+            if progress in (0, 100):
                 p.setBrush(QPalette.ColorRole.Base, backgroundColor)
                 p.setBrush(QPalette.ColorRole.Text, foregroundColor)
             else:
--- a/eric6/WebBrowser/WebBrowserTabBar.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/eric6/WebBrowser/WebBrowserTabBar.py	Thu Apr 08 18:27:47 2021 +0200
@@ -118,10 +118,7 @@
                         0, lambda: self.__showTabPreview(tabIndex))
             
             # If current tab or not found then hide previous tab preview
-            if (
-                tabIndex == self.currentIndex() or
-                tabIndex == -1
-            ):
+            if tabIndex in (self.currentIndex(), -1):
                 self.__hidePreview()
     
     def leaveEvent(self, evt):
--- a/scripts/install.py	Thu Apr 08 17:27:12 2021 +0200
+++ b/scripts/install.py	Thu Apr 08 18:27:47 2021 +0200
@@ -740,7 +740,7 @@
     try:
         # Install the files
         # make the install directories
-        for key in cfg.keys():
+        for key in cfg:
             if cfg[key] and not os.path.isdir(cfg[key]):
                 os.makedirs(cfg[key])
         

eric ide

mercurial