Wed, 14 Apr 2021 19:59:16 +0200
Applied some more code simplifications suggested by the new Simplify checker (Y105: use contextlib.suppress) (batch 1).
--- a/eric6/DataViews/PyCoverageDialog.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/DataViews/PyCoverageDialog.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import pyqtSlot, Qt from PyQt5.QtWidgets import ( @@ -387,10 +388,8 @@ """ files = Utilities.direntries(self.path, True, '*,cover', False) for file in files: - try: + with contextlib.suppress(OSError): os.remove(file) - except OSError: - pass @pyqtSlot() def on_reloadButton_clicked(self):
--- a/eric6/DebugClients/Python/BreakpointWatch.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/DebugClients/Python/BreakpointWatch.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib class Breakpoint: @@ -226,10 +227,8 @@ """ Public method to clear this watch expression. """ - try: + with contextlib.suppress(ValueError): del Watch.watches[self] - except ValueError: - pass def enable(self): """ @@ -251,10 +250,8 @@ @param cond expression of the watch expression to be cleared @type str """ - try: + with contextlib.suppress(ValueError): Watch.watches.remove(Watch.get_watch(cond)) - except ValueError: - pass @staticmethod def clear_all_watches():
--- a/eric6/DebugClients/Python/DebugBase.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/DebugClients/Python/DebugBase.py Wed Apr 14 19:59:16 2021 +0200 @@ -15,6 +15,7 @@ import ctypes import time import dis +import contextlib from BreakpointWatch import Breakpoint, Watch @@ -168,13 +169,11 @@ cf = cf.f_back frmnr -= 1 - try: + with contextlib.suppress(Exception): if "__pypy__" in sys.builtin_module_names: import __pypy__ __pypy__.locals_to_fast(cf) return - except Exception: # secok - pass ctypes.pythonapi.PyFrame_LocalsToFast( ctypes.py_object(cf),
--- a/eric6/DebugClients/Python/DebugClientBase.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/DebugClients/Python/DebugClientBase.py Wed Apr 14 19:59:16 2021 +0200 @@ -22,7 +22,7 @@ import types import importlib.util import fnmatch - +import contextlib import DebugClientCapabilities import DebugVariables @@ -239,10 +239,8 @@ @param terminate flag indicating to terminate (boolean) """ - try: + with contextlib.suppress(Exception): self.set_quit() - except Exception: # secok - pass self.debugging = False self.multiprocessSupport = False @@ -1146,10 +1144,8 @@ """ try: import PyProfile # __IGNORE_WARNING__ - try: + with contextlib.suppress(KeyError): del sys.modules['PyProfile'] - except KeyError: - pass return self.clientCapabilities except ImportError: return (
--- a/eric6/DebugClients/Python/DebugVariables.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/DebugClients/Python/DebugVariables.py Wed Apr 14 19:59:16 2021 +0200 @@ -7,6 +7,8 @@ Module implementing classes and functions to dump variable contents. """ +import contextlib + from DebugConfig import ConfigQtNames, ConfigKnownQtTypes, BatchSize # @@ -653,10 +655,8 @@ (frozenset, setResolver), ] - try: + with contextlib.suppress(Exception): _TypeMap.append((long, None)) # __IGNORE_WARNING__ - except Exception: # secok - pass # not available on all Python versions try: import array
--- a/eric6/DebugClients/Python/PyProfile.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/DebugClients/Python/PyProfile.py Wed Apr 14 19:59:16 2021 +0200 @@ -11,6 +11,7 @@ import profile import atexit import pickle # secok +import contextlib class PyProfile(profile.Profile): @@ -64,11 +65,9 @@ Public method to store the collected profile data. """ # dump the raw timing data - try: - with open(self.timingCache, 'wb') as cache: - marshal.dump(self.timings, cache) - except OSError: - pass + with contextlib.suppress(OSError), \ + open(self.timingCache, 'wb') as cache: + marshal.dump(self.timings, cache) # dump the profile data self.dump_stats(self.profileCache)
--- a/eric6/DebugClients/Python/ThreadExtension.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/DebugClients/Python/ThreadExtension.py Wed Apr 14 19:59:16 2021 +0200 @@ -9,6 +9,7 @@ import os import sys +import contextlib import _thread import threading @@ -95,9 +96,8 @@ """ self.lockClient() try: - del self.threads[threadId] - except KeyError: - pass + with contextlib.suppress(KeyError): + del self.threads[threadId] finally: self.unlockClient() @@ -116,10 +116,8 @@ """ Public method to release the lock for this client. """ - try: + with contextlib.suppress(RuntimeError): self.clientLock.release() - except RuntimeError: - pass def setCurrentThread(self, threadId): """
--- a/eric6/Debugger/DebugServer.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Debugger/DebugServer.py Wed Apr 14 19:59:16 2021 +0200 @@ -9,6 +9,7 @@ import os import shlex +import contextlib from PyQt5.QtCore import pyqtSignal, pyqtSlot, QModelIndex from PyQt5.QtNetwork import ( @@ -425,10 +426,8 @@ @rtype list of str """ languages = list(self.__debuggerInterfaceRegistry.keys()) - try: + with contextlib.suppress(ValueError): languages.remove("None") - except ValueError: - pass # it is not in the list if shellOnly: languages = [lang for lang in languages
--- a/eric6/Debugger/DebuggerInterfacePython.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Debugger/DebuggerInterfacePython.py Wed Apr 14 19:59:16 2021 +0200 @@ -11,6 +11,7 @@ import os import logging import shlex +import contextlib from PyQt5.QtCore import ( QObject, QProcess, QProcessEnvironment, QTimer @@ -601,12 +602,10 @@ if not self.__connections: # no active connections anymore - try: + with contextlib.suppress(RuntimeError): self.debugServer.signalLastClientExited() - except RuntimeError: # debug server object might have been deleted already # ignore this - pass self.__autoContinued.clear() self.debugServer.startClient()
--- a/eric6/Debugger/VariablesViewer.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Debugger/VariablesViewer.py Wed Apr 14 19:59:16 2021 +0200 @@ -9,6 +9,7 @@ import ast import re +import contextlib from PyQt5.QtCore import ( Qt, QAbstractItemModel, QModelIndex, QCoreApplication, @@ -201,10 +202,8 @@ elif dtype == 'str': if VariableItem.rx_nonprintable.search(dvalue) is None: - try: + with contextlib.suppress(Exception): dvalue = ast.literal_eval(dvalue) - except Exception: # secok - pass dvalue = str(dvalue) self.value = dvalue
--- a/eric6/E5Network/E5SslCertificateSelectionDialog.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/E5Network/E5SslCertificateSelectionDialog.py Wed Apr 14 19:59:16 2021 +0200 @@ -7,12 +7,12 @@ Module implementing a dialog to select a SSL certificate. """ +import contextlib + from PyQt5.QtCore import pyqtSlot, Qt from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QTreeWidgetItem -try: +with contextlib.suppress(ImportError): from PyQt5.QtNetwork import QSslCertificate -except ImportError: - pass from .Ui_E5SslCertificateSelectionDialog import ( Ui_E5SslCertificateSelectionDialog
--- a/eric6/E5Network/E5SslCertificatesDialog.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/E5Network/E5SslCertificatesDialog.py Wed Apr 14 19:59:16 2021 +0200 @@ -7,16 +7,16 @@ Module implementing a dialog to show and edit all certificates. """ +import contextlib + from PyQt5.QtCore import ( pyqtSlot, Qt, QByteArray, QFile, QFileInfo, QIODevice ) from PyQt5.QtWidgets import QDialog, QTreeWidgetItem -try: +with contextlib.suppress(ImportError): from PyQt5.QtNetwork import ( QSslCertificate, QSslSocket, QSslConfiguration, QSsl ) -except ImportError: - pass from E5Gui import E5MessageBox, E5FileDialog
--- a/eric6/E5XML/TasksReader.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/E5XML/TasksReader.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import time +import contextlib from E5Gui.E5Application import e5App @@ -135,9 +136,7 @@ self.readElementText() ) elif self.name() == "Linenumber": - try: + with contextlib.suppress(ValueError): task["linenumber"] = int(self.readElementText()) - except ValueError: - pass else: self.raiseUnexpectedStartTag(self.name())
--- a/eric6/Globals/__init__.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Globals/__init__.py Wed Apr 14 19:59:16 2021 +0200 @@ -15,6 +15,7 @@ import os import re import shutil +import contextlib from PyQt5.QtCore import ( QDir, QByteArray, QCoreApplication, QT_VERSION, QProcess, qVersion @@ -372,11 +373,8 @@ # step 1: extract suffix version = re.split(r"[^\d.]", version)[0] for part in version.split("."): - try: + with contextlib.suppress(ValueError): versionParts.append(int(part.strip())) - except ValueError: - # skip non-integer parts - pass versionParts.extend([0] * length) return tuple(versionParts[:length])
--- a/eric6/HexEdit/HexEditMainWindow.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/HexEdit/HexEditMainWindow.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import ( pyqtSignal, pyqtSlot, QFile, QFileInfo, QSize, QCoreApplication, QLocale @@ -919,12 +920,10 @@ Preferences.setGeometry("HexEditorGeometry", self.saveGeometry()) - try: + with contextlib.suppress(ValueError): if self.__fromEric or len(self.__class__.windows) > 1: del self.__class__.windows[ self.__class__.windows.index(self)] - except ValueError: - pass if not self.__fromEric: Preferences.syncPreferences()
--- a/eric6/IconEditor/IconEditorWindow.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/IconEditor/IconEditorWindow.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import ( pyqtSignal, Qt, QSize, QSignalMapper, QFileInfo, QFile, QEvent @@ -154,10 +155,8 @@ inputFormats = [] readFormats = QImageReader.supportedImageFormats() for readFormat in readFormats: - try: + with contextlib.suppress(KeyError): inputFormats.append(filters[bytes(readFormat).decode()]) - except KeyError: - pass inputFormats.sort() inputFormats.append(self.tr("All Files (*)")) self.__inputFilter = ';;'.join(inputFormats) @@ -165,10 +164,8 @@ outputFormats = [] writeFormats = QImageWriter.supportedImageFormats() for writeFormat in writeFormats: - try: + with contextlib.suppress(KeyError): outputFormats.append(filters[bytes(writeFormat).decode()]) - except KeyError: - pass outputFormats.sort() self.__outputFilter = ';;'.join(outputFormats) @@ -1027,12 +1024,10 @@ Preferences.setGeometry("IconEditorGeometry", self.saveGeometry()) - try: + with contextlib.suppress(ValueError): if self.fromEric or len(self.__class__.windows) > 1: del self.__class__.windows[ self.__class__.windows.index(self)] - except ValueError: - pass if not self.fromEric: Preferences.syncPreferences()
--- a/eric6/MultiProject/MultiProject.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/MultiProject/MultiProject.py Wed Apr 14 19:59:16 2021 +0200 @@ -9,6 +9,7 @@ import os import shutil +import contextlib from PyQt5.QtCore import ( pyqtSignal, pyqtSlot, QFileInfo, QFile, QIODevice, QObject, QUuid @@ -964,10 +965,8 @@ @param actions list of actions (list of E5Action) """ for act in actions: - try: + with contextlib.suppress(ValueError): self.actions.remove(act) - except ValueError: - pass def getMenu(self, menuName): """
--- a/eric6/MultiProject/MultiProjectFile.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/MultiProject/MultiProjectFile.py Wed Apr 14 19:59:16 2021 +0200 @@ -67,7 +67,7 @@ jsonString = json.dumps(multiProjectDict, indent=2) with open(filename, "w") as f: f.write(jsonString) - except (TypeError, EnvironmentError) as err: + except (TypeError, OSError) as err: with E5OverridenCursor(): E5MessageBox.critical( None, @@ -95,7 +95,7 @@ with open(filename, "r") as f: jsonString = f.read() multiProjectDict = json.loads(jsonString) - except (EnvironmentError, json.JSONDecodeError) as err: + except (OSError, json.JSONDecodeError) as err: E5MessageBox.critical( None, self.tr("Read Multi Project File"),
--- a/eric6/PipInterface/Pip.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/PipInterface/Pip.py Wed Apr 14 19:59:16 2021 +0200 @@ -10,6 +10,7 @@ import os import sys import json +import contextlib from PyQt5.QtCore import pyqtSlot, QObject, QProcess, QUrl, QCoreApplication from PyQt5.QtWidgets import QDialog, QInputDialog, QLineEdit @@ -127,10 +128,8 @@ # Windows: %APPDATA%\pip\pip.ini # Environment: $PIP_CONFIG_FILE - try: + with contextlib.suppress(KeyError): return os.environ["PIP_CONFIG_FILE"] - except KeyError: - pass if Globals.isWindowsPlatform(): config = os.path.join(os.environ["APPDATA"], "pip", "pip.ini") @@ -683,11 +682,8 @@ data = str(reply.readAll(), Preferences.getSystem("IOEncoding"), 'replace') - try: + with contextlib.suppress(Exception): result = json.loads(data) - except Exception: # secok - # ignore JSON exceptions - pass return result
--- a/eric6/PipInterface/PipPackagesWidget.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/PipInterface/PipPackagesWidget.py Wed Apr 14 19:59:16 2021 +0200 @@ -10,6 +10,7 @@ import textwrap import os import html.parser +import contextlib from PyQt5.QtCore import pyqtSlot, Qt, QUrl, QUrlQuery from PyQt5.QtNetwork import QNetworkReply, QNetworkRequest @@ -1213,12 +1214,8 @@ return if not os.path.exists(cfgFile): - try: - with open(cfgFile, "w") as f: - f.write("[global]\n") - except OSError: - # ignore these - pass + with contextlib.suppress(OSError), open(cfgFile, "w") as f: + f.write("[global]\n") # check, if the destination is writeable if not os.access(cfgFile, os.W_OK):
--- a/eric6/PluginManager/PluginInstallDialog.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/PluginManager/PluginInstallDialog.py Wed Apr 14 19:59:16 2021 +0200 @@ -13,10 +13,8 @@ import zipfile import compileall import glob -try: # Py3 - import urllib.parse as parse -except (ImportError): - import urlparse as parse # __IGNORE_WARNING__ +import contextlib +import urllib.parse from PyQt5.QtCore import pyqtSlot, Qt, QDir, QFileInfo from PyQt5.QtWidgets import ( @@ -267,7 +265,7 @@ self.destinationCombo.currentIndex()) # check if archive is a local url - url = parse.urlparse(archive) + url = urllib.parse.urlparse(archive) if url[0].lower() == 'file': archive = url[2] @@ -351,10 +349,8 @@ needsRestart = tokens[1].strip() == "True" elif line.startswith("pyqtApi"): tokens = line.split("=") - try: + with contextlib.suppress(ValueError): pyqtApi = int(tokens[1].strip()) - except ValueError: - pass elif line.startswith("doNotCompile"): tokens = line.split("=") if tokens[1].strip() == "True":
--- a/eric6/PluginManager/PluginManager.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/PluginManager/PluginManager.py Wed Apr 14 19:59:16 2021 +0200 @@ -12,6 +12,7 @@ import zipfile import types import importlib +import contextlib from PyQt5.QtCore import ( pyqtSignal, QObject, QDate, QFile, QFileInfo, QUrl, QIODevice @@ -643,18 +644,14 @@ if onDemand: self.__onDemandInactiveModules.pop(name) - try: + with contextlib.suppress(KeyError): self.__onDemandInactivePlugins.pop(name) - except KeyError: - pass self.__onDemandActivePlugins[name] = pluginObject self.__onDemandActiveModules[name] = module else: self.__inactiveModules.pop(name) - try: + with contextlib.suppress(KeyError): self.__inactivePlugins.pop(name) - except KeyError: - pass self.__activePlugins[name] = pluginObject self.__activeModules[name] = module return obj @@ -739,10 +736,8 @@ self.__onDemandInactiveModules[name] = module else: self.__activeModules.pop(name) - try: + with contextlib.suppress(KeyError): self.__activePlugins.pop(name) - except KeyError: - pass self.__inactivePlugins[name] = pluginObject self.__inactiveModules[name] = module
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleFixer.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleFixer.py Wed Apr 14 19:59:16 2021 +0200 @@ -10,14 +10,13 @@ import os import re import tokenize +import contextlib from io import StringIO # CodeStyleCheckerDialog tries to import FixableCodeStyleIssues which fails # under Python3. So ignore it. -try: +with contextlib.suppress(ImportError): import pycodestyle -except ImportError: - pass FixableCodeStyleIssues = [ "D111", "D112", "D121", "D131", "D141", "D142", @@ -209,16 +208,10 @@ bfn = '{0}~'.format(os.path.realpath(self.__filename)) else: bfn = '{0}~'.format(self.__filename) - try: + with contextlib.suppress(OSError): os.remove(bfn) - except OSError: - # if there was an error, ignore it - pass - try: + with contextlib.suppress(OSError): os.rename(self.__filename, bfn) - except OSError: - # if there was an error, ignore it - pass txt = "".join(self.__source) try:
--- a/eric6/Plugins/PluginCodeStyleChecker.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Plugins/PluginCodeStyleChecker.py Wed Apr 14 19:59:16 2021 +0200 @@ -9,6 +9,7 @@ import os import textwrap +import contextlib from PyQt5.QtCore import QObject, pyqtSignal, QCoreApplication @@ -417,10 +418,8 @@ @param editor reference to the editor (QScintilla.Editor) """ - try: + with contextlib.suppress(ValueError): self.__editors.remove(editor) - except ValueError: - pass def __editorShowMenu(self, menuName, menu, editor): """
--- a/eric6/Plugins/PluginSyntaxChecker.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Plugins/PluginSyntaxChecker.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import QObject @@ -339,10 +340,8 @@ @param editor reference to the editor (QScintilla.Editor) """ - try: + with contextlib.suppress(ValueError): self.__editors.remove(editor) - except ValueError: - pass def __editorShowMenu(self, menuName, menu, editor): """
--- a/eric6/Plugins/PluginVcsGit.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Plugins/PluginVcsGit.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import QObject, QCoreApplication, QTranslator, QByteArray @@ -196,11 +197,9 @@ from VcsPlugins.vcsGit.ProjectHelper import GitProjectHelper self.__projectHelperObject = GitProjectHelper(None, None) - try: + with contextlib.suppress(KeyError): e5App().registerPluginObject( pluginTypename, self.__projectHelperObject, pluginType) - except KeyError: - pass # ignore duplicate registration readShortcuts(pluginName=pluginTypename)
--- a/eric6/Plugins/PluginVcsMercurial.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Plugins/PluginVcsMercurial.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import QObject, QCoreApplication, QByteArray @@ -197,11 +198,9 @@ from VcsPlugins.vcsMercurial.ProjectHelper import HgProjectHelper self.__projectHelperObject = HgProjectHelper(None, None) - try: + with contextlib.suppress(KeyError): e5App().registerPluginObject( pluginTypename, self.__projectHelperObject, pluginType) - except KeyError: - pass # ignore duplicate registration readShortcuts(pluginName=pluginTypename) def getProjectHelper(self):
--- a/eric6/Plugins/PluginVcsPySvn.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Plugins/PluginVcsPySvn.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import QObject, QCoreApplication @@ -160,11 +161,9 @@ from VcsPlugins.vcsPySvn.ProjectHelper import PySvnProjectHelper self.__projectHelperObject = PySvnProjectHelper(None, None) - try: + with contextlib.suppress(KeyError): e5App().registerPluginObject( pluginTypename, self.__projectHelperObject, pluginType) - except KeyError: - pass # ignore duplicate registration readShortcuts(pluginName=pluginTypename) def getProjectHelper(self):
--- a/eric6/Plugins/PluginVcsSubversion.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Plugins/PluginVcsSubversion.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import QObject, QCoreApplication @@ -166,11 +167,9 @@ from VcsPlugins.vcsSubversion.ProjectHelper import SvnProjectHelper self.__projectHelperObject = SvnProjectHelper(None, None) - try: + with contextlib.suppress(KeyError): e5App().registerPluginObject( pluginTypename, self.__projectHelperObject, pluginType) - except KeyError: - pass # ignore duplicate registration readShortcuts(pluginName=pluginTypename) def getProjectHelper(self):
--- a/eric6/Plugins/UiExtensionPlugins/Translator/TranslatorEngines/TranslationEngine.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Plugins/UiExtensionPlugins/Translator/TranslatorEngines/TranslationEngine.py Wed Apr 14 19:59:16 2021 +0200 @@ -7,6 +7,8 @@ Module implementing the translation engine base class. """ +import contextlib + from PyQt5.QtCore import pyqtSignal, QObject @@ -62,11 +64,8 @@ @rtype list of str """ targetLanguages = self.supportedLanguages()[:] - try: + with contextlib.suppress(ValueError): targetLanguages.remove(original) - except ValueError: - # original is not in the list of target languages - pass return targetLanguages
--- a/eric6/Plugins/VcsPlugins/vcsGit/ConfigurationPage/GitPage.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsGit/ConfigurationPage/GitPage.py Wed Apr 14 19:59:16 2021 +0200 @@ -9,6 +9,7 @@ """ import os +import contextlib from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QDialog @@ -93,13 +94,9 @@ else: firstName, lastName, email = ( "Firstname", "Lastname", "email_address") - try: - with open(cfgFile, "w") as f: - f.write("[user]\n") - f.write(" name = {0} {1}\n".format(firstName, lastName)) - f.write(" email = {0}\n".format(email)) - except OSError: - # ignore these - pass + with contextlib.suppress(OSError), open(cfgFile, "w") as f: + f.write("[user]\n") + f.write(" name = {0} {1}\n".format(firstName, lastName)) + f.write(" email = {0}\n".format(email)) editor = MiniEditor(cfgFile, "Properties", self) editor.show()
--- a/eric6/Plugins/VcsPlugins/vcsGit/git.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsGit/git.py Wed Apr 14 19:59:16 2021 +0200 @@ -10,6 +10,7 @@ import os import shutil import re +import contextlib from PyQt5.QtCore import QProcess, pyqtSignal, QFileInfo from PyQt5.QtWidgets import QApplication, QDialog, QInputDialog, QLineEdit @@ -1166,10 +1167,8 @@ entries.extend(Utilities.direntries(name, True, pat)) for entry in entries: - try: + with contextlib.suppress(OSError): os.remove(entry) - except OSError: - pass def vcsCommandLine(self, name): """ @@ -3572,10 +3571,7 @@ cfgFile = os.path.join(repodir, self.adminDir, "config") if not os.path.exists(cfgFile): # create an empty one - try: - with open(cfgFile, "w"): - pass - except OSError: + with contextlib.suppress(OSError), open(cfgFile, "w"): pass self.repoEditor = MiniEditor(cfgFile, "Properties") self.repoEditor.show() @@ -3594,14 +3590,10 @@ else: firstName, lastName, email = ( "Firstname", "Lastname", "email_address") - try: - with open(cfgFile, "w") as f: - f.write("[user]\n") - f.write(" name = {0} {1}\n".format(firstName, lastName)) - f.write(" email = {0}\n".format(email)) - except OSError: - # ignore these - pass + with contextlib.suppress(OSError), open(cfgFile, "w") as f: + f.write("[user]\n") + f.write(" name = {0} {1}\n".format(firstName, lastName)) + f.write(" email = {0}\n".format(email)) self.userEditor = MiniEditor(cfgFile, "Properties") self.userEditor.show()
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/HgLogBrowserDialog.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsMercurial/HgLogBrowserDialog.py Wed Apr 14 19:59:16 2021 +0200 @@ -10,6 +10,7 @@ import os import re import collections +import contextlib from PyQt5.QtCore import pyqtSlot, Qt, QDate, QSize, QPoint, QFileInfo from PyQt5.QtGui import ( @@ -2276,11 +2277,8 @@ revs = [] for itm in selectedItems: rev = itm.text(self.RevisionColumn).split(":", 1)[0] - try: + with contextlib.suppress(ValueError): revs.append(int(rev)) - except ValueError: - # ignore silently - pass baseRev = min(revs) while baseRev in revs: revs.remove(baseRev)
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/hg.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsMercurial/hg.py Wed Apr 14 19:59:16 2021 +0200 @@ -9,6 +9,7 @@ import os import shutil +import contextlib from PyQt5.QtCore import ( pyqtSignal, QFileInfo, QFileSystemWatcher, QCoreApplication @@ -1140,10 +1141,8 @@ entries.extend(Utilities.direntries(name, True, pat)) for entry in entries: - try: + with contextlib.suppress(OSError): os.remove(entry) - except OSError: - pass def vcsCommandLine(self, name): """
--- a/eric6/Plugins/VcsPlugins/vcsPySvn/SvnUtilities.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsPySvn/SvnUtilities.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import QDateTime, Qt @@ -74,15 +75,10 @@ Module function to create a default config file suitable for eric. """ config = getConfigPath() - try: + with contextlib.suppress(OSError): os.makedirs(os.path.dirname(config)) - except OSError: - pass - try: - with open(config, "w") as f: - f.write(DefaultConfig) - except OSError: - pass + with contextlib.suppress(OSError), open(config, "w") as f: + f.write(DefaultConfig) def amendConfig(): @@ -127,8 +123,5 @@ newConfig.append(line) if newConfig != configList: - try: - with open(config, "w") as f: - f.write("\n".join(newConfig)) - except OSError: - pass + with contextlib.suppress(OSError), open(config, "w") as f: + f.write("\n".join(newConfig))
--- a/eric6/Plugins/VcsPlugins/vcsSubversion/SvnUtilities.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsSubversion/SvnUtilities.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib import Utilities @@ -47,15 +48,10 @@ Module function to create a default config file suitable for eric. """ config = getConfigPath() - try: + with contextlib.suppress(OSError): os.makedirs(os.path.dirname(config)) - except OSError: - pass - try: - with open(config, "w") as f: - f.write(DefaultConfig) - except OSError: - pass + with contextlib.suppress(OSError), open(config, "w") as f: + f.write(DefaultConfig) def amendConfig(): @@ -100,8 +96,5 @@ newConfig.append(line) if newConfig != configList: - try: - with open(config, "w") as f: - f.write("\n".join(newConfig)) - except OSError: - pass + with contextlib.suppress(OSError), open(config, "w") as f: + f.write("\n".join(newConfig))
--- a/eric6/Preferences/HighlightingStylesFile.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Preferences/HighlightingStylesFile.py Wed Apr 14 19:59:16 2021 +0200 @@ -83,7 +83,7 @@ jsonString = json.dumps(stylesDict, indent=2) with open(filename, "w") as f: f.write(jsonString) - except (TypeError, EnvironmentError) as err: + except (TypeError, OSError) as err: with E5OverridenCursor(): E5MessageBox.critical( None, @@ -111,7 +111,7 @@ with open(filename, "r") as f: jsonString = f.read() stylesDict = json.loads(jsonString) - except (EnvironmentError, json.JSONDecodeError) as err: + except (OSError, json.JSONDecodeError) as err: E5MessageBox.critical( None, self.tr("Import Highlighting Styles"),
--- a/eric6/Preferences/ShortcutsFile.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Preferences/ShortcutsFile.py Wed Apr 14 19:59:16 2021 +0200 @@ -162,7 +162,7 @@ jsonString = json.dumps(shortcutsDict, indent=2) with open(filename, "w") as f: f.write(jsonString) - except (TypeError, EnvironmentError) as err: + except (TypeError, OSError) as err: with E5OverridenCursor(): E5MessageBox.critical( None, @@ -192,7 +192,7 @@ with open(filename, "r") as f: jsonString = f.read() shortcutsDict = json.loads(jsonString) - except (EnvironmentError, json.JSONDecodeError) as err: + except (OSError, json.JSONDecodeError) as err: E5MessageBox.critical( None, self.tr("Import Keyboard Shortcuts"),
--- a/eric6/Project/DebuggerPropertiesFile.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Project/DebuggerPropertiesFile.py Wed Apr 14 19:59:16 2021 +0200 @@ -68,7 +68,7 @@ jsonString = json.dumps(debuggerPropertiesDict, indent=2) with open(filename, "w") as f: f.write(jsonString) - except (TypeError, EnvironmentError) as err: + except (TypeError, OSError) as err: with E5OverridenCursor(): E5MessageBox.critical( None, @@ -97,7 +97,7 @@ with open(filename, "r") as f: jsonString = f.read() debuggerPropertiesDict = json.loads(jsonString) - except (EnvironmentError, json.JSONDecodeError) as err: + except (OSError, json.JSONDecodeError) as err: E5MessageBox.critical( None, self.tr("Read Debugger Properties"),
--- a/eric6/Project/Project.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Project/Project.py Wed Apr 14 19:59:16 2021 +0200 @@ -14,6 +14,7 @@ import fnmatch import copy import zipfile +import contextlib from PyQt5.QtCore import ( pyqtSlot, QFile, QFileInfo, pyqtSignal, QCryptographicHash, QIODevice, @@ -644,13 +645,11 @@ self.pdata["FILETYPES"]["*.qm"] = "TRANSLATIONS" # Project type specific ones - try: + with contextlib.suppress(KeyError): if self.__fileTypeCallbacks[ self.pdata["PROJECTTYPE"]] is not None: ftypes = self.__fileTypeCallbacks[self.pdata["PROJECTTYPE"]]() self.pdata["FILETYPES"].update(ftypes) - except KeyError: - pass self.setDirty(True) @@ -668,7 +667,7 @@ self.pdata["FILETYPES"]["*.ts"] = "TRANSLATIONS" if "*.qm" not in self.pdata["FILETYPES"]: self.pdata["FILETYPES"]["*.qm"] = "TRANSLATIONS" - try: + with contextlib.suppress(KeyError): if self.__fileTypeCallbacks[ self.pdata["PROJECTTYPE"]] is not None: ftypes = self.__fileTypeCallbacks[self.pdata["PROJECTTYPE"]]() @@ -676,8 +675,6 @@ if pattern not in self.pdata["FILETYPES"]: self.pdata["FILETYPES"][pattern] = ftype self.setDirty(True) - except KeyError: - pass def __loadRecent(self): """ @@ -2920,11 +2917,9 @@ # try project type specific defaults next projectType = self.pdata["PROJECTTYPE"] - try: + with contextlib.suppress(KeyError): if self.__lexerAssociationCallbacks[projectType] is not None: return self.__lexerAssociationCallbacks[projectType](filename) - except KeyError: - pass # return empty string to signal to use the global setting return "" @@ -4782,10 +4777,8 @@ @param actions list of actions (list of E5Action) """ for act in actions: - try: + with contextlib.suppress(ValueError): self.actions.remove(act) - except ValueError: - pass def getMenu(self, menuName): """
--- a/eric6/Project/ProjectFile.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Project/ProjectFile.py Wed Apr 14 19:59:16 2021 +0200 @@ -9,6 +9,7 @@ import json import time +import contextlib import typing from PyQt5.QtCore import QObject @@ -69,30 +70,24 @@ "SOURCES", "FORMS", "TRANSLATIONS", "TRANSLATIONEXCEPTIONS", "RESOURCES", "INTERFACES", "PROTOCOLS", "OTHERS" ): - try: + with contextlib.suppress(KeyError): projectDict["project"][key] = [ Utilities.fromNativeSeparators(f) for f in projectDict["project"][key] ] - except KeyError: - # ignore non-existent elements - pass for key in ( "SPELLWORDS", "SPELLEXCLUDES", "TRANSLATIONPATTERN", "TRANSLATIONSBINPATH", "MAINSCRIPT" ): - try: + with contextlib.suppress(KeyError): projectDict["project"][key] = Utilities.fromNativeSeparators( projectDict["project"][key]) - except KeyError: - # ignore non-existent elements - pass try: jsonString = json.dumps(projectDict, indent=2, sort_keys=True) with open(filename, "w", newline="") as f: f.write(jsonString) - except (TypeError, EnvironmentError) as err: + except (TypeError, OSError) as err: with E5OverridenCursor(): E5MessageBox.critical( None, @@ -119,7 +114,7 @@ with open(filename, "r") as f: jsonString = f.read() projectDict = json.loads(jsonString) - except (EnvironmentError, json.JSONDecodeError) as err: + except (OSError, json.JSONDecodeError) as err: E5MessageBox.critical( None, self.tr("Read Project File"), @@ -135,24 +130,18 @@ "SOURCES", "FORMS", "TRANSLATIONS", "TRANSLATIONEXCEPTIONS", "RESOURCES", "INTERFACES", "PROTOCOLS", "OTHERS" ): - try: + with contextlib.suppress(KeyError): projectDict["project"][key] = [ Utilities.toNativeSeparators(f) for f in projectDict["project"][key] ] - except KeyError: - # ignore non-existent elements - pass for key in ( "SPELLWORDS", "SPELLEXCLUDES", "TRANSLATIONPATTERN", "TRANSLATIONSBINPATH", "MAINSCRIPT" ): - try: + with contextlib.suppress(KeyError): projectDict["project"][key] = Utilities.toNativeSeparators( projectDict["project"][key]) - except KeyError: - # ignore non-existent elements - pass self.__project.pdata = projectDict["project"]
--- a/eric6/Project/ProjectFormsBrowser.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Project/ProjectFormsBrowser.py Wed Apr 14 19:59:16 2021 +0200 @@ -10,6 +10,7 @@ import os import sys import shutil +import contextlib from PyQt5.QtCore import QThread, QFileInfo, pyqtSignal, QProcess from PyQt5.QtWidgets import QDialog, QInputDialog, QApplication, QMenu @@ -501,15 +502,13 @@ """ itmList = self.getSelectedItems() for itm in itmList[:]: - try: + with contextlib.suppress(Exception): if isinstance(itm, ProjectBrowserFileItem): # hook support if self.hooks["open"] is not None: self.hooks["open"](itm.fileName()) else: self.designerFile.emit(itm.fileName()) - except Exception: # secok - pass def __openFileInEditor(self): """
--- a/eric6/Project/UicLoadUi5.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Project/UicLoadUi5.py Wed Apr 14 19:59:16 2021 +0200 @@ -11,6 +11,7 @@ import sys import json import xml.etree.ElementTree # secok +import contextlib try: from PyQt5.QtCore import QMetaMethod, QByteArray @@ -20,10 +21,8 @@ print("PyQt5 could not be found.") sys.exit(1) -try: +with contextlib.suppress(ImportError): from PyQt5 import QtWebEngineWidgets # __IGNORE_WARNING__ -except ImportError: - pass sys.path.append(os.path.dirname(os.path.dirname(__file__))) # add the eric package directory
--- a/eric6/Project/UicLoadUi6.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Project/UicLoadUi6.py Wed Apr 14 19:59:16 2021 +0200 @@ -11,6 +11,7 @@ import sys import json import xml.etree.ElementTree # secok +import contextlib try: from PyQt6.QtCore import QMetaMethod, QByteArray @@ -21,10 +22,8 @@ print("PyQt6 could not be found.") sys.exit(1) -try: +with contextlib.suppress(ImportError): from PyQt6 import QtWebEngineWidgets # __IGNORE_WARNING__ -except ImportError: - pass sys.path.append(os.path.dirname(os.path.dirname(__file__))) # add the eric package directory
--- a/eric6/Project/UserProjectFile.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Project/UserProjectFile.py Wed Apr 14 19:59:16 2021 +0200 @@ -64,7 +64,7 @@ jsonString = json.dumps(userProjectDict, indent=2) with open(filename, "w") as f: f.write(jsonString) - except (TypeError, EnvironmentError) as err: + except (TypeError, OSError) as err: with E5OverridenCursor(): E5MessageBox.critical( None, @@ -93,7 +93,7 @@ with open(filename, "r") as f: jsonString = f.read() userProjectDict = json.loads(jsonString) - except (EnvironmentError, json.JSONDecodeError) as err: + except (OSError, json.JSONDecodeError) as err: E5MessageBox.critical( None, self.tr("Read User Project Properties"),
--- a/eric6/PyUnit/UnittestDialog.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/PyUnit/UnittestDialog.py Wed Apr 14 19:59:16 2021 +0200 @@ -12,6 +12,7 @@ import time import re import os +import contextlib from PyQt5.QtCore import pyqtSignal, QEvent, Qt, pyqtSlot from PyQt5.QtGui import QColor @@ -1230,11 +1231,8 @@ event.accept() for editor in self.__editors: - try: + with contextlib.suppress(Exception): editor.close() - except Exception: # secok - # ignore all exceptions - pass class QtTestResult(unittest.TestResult):
--- a/eric6/QScintilla/Editor.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/QScintilla/Editor.py Wed Apr 14 19:59:16 2021 +0200 @@ -10,6 +10,7 @@ import os import re import difflib +import contextlib from PyQt5.QtCore import ( pyqtSignal, pyqtSlot, Qt, QDir, QTimer, QModelIndex, QFileInfo, @@ -3250,16 +3251,10 @@ except OSError: # if there was an error, ignore it perms_valid = False - try: + with contextlib.suppress(OSError): os.remove(bfn) - except OSError: - # if there was an error, ignore it - pass - try: + with contextlib.suppress(OSError): os.rename(fn, bfn) - except OSError: - # if there was an error, ignore it - pass # now write text to the file fn try:
--- a/eric6/QScintilla/Lexers/LexerPygments.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/QScintilla/Lexers/LexerPygments.py Wed Apr 14 19:59:16 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a custom lexer using pygments. """ +import contextlib + from pygments.token import Token from pygments.lexers import ( guess_lexer_for_filename, guess_lexer, find_lexer_class @@ -453,17 +455,13 @@ if self.editor is not None: fn = self.editor.getFileName() if fn: - try: + with contextlib.suppress(ClassNotFound): lexer = guess_lexer_for_filename(fn, text) - except ClassNotFound: - pass # step 2: guess on text only if lexer is None: - try: + with contextlib.suppress(ClassNotFound): lexer = guess_lexer(text) - except ClassNotFound: - pass return lexer
--- a/eric6/QScintilla/MarkupProviders/ImageMarkupDialog.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/QScintilla/MarkupProviders/ImageMarkupDialog.py Wed Apr 14 19:59:16 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a dialog to enter data for an image markup. """ +import contextlib + from PyQt5.QtCore import pyqtSlot, QSize from PyQt5.QtGui import QImage, QImageReader from PyQt5.QtWidgets import QDialog, QDialogButtonBox @@ -79,10 +81,8 @@ inputFormats = [] readFormats = QImageReader.supportedImageFormats() for readFormat in readFormats: - try: + with contextlib.suppress(KeyError): inputFormats.append(filters[bytes(readFormat).decode()]) - except KeyError: - pass inputFormats.sort() inputFormats.append(self.tr("All Files (*)")) if filters["png"] in inputFormats:
--- a/eric6/QScintilla/Shell.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/QScintilla/Shell.py Wed Apr 14 19:59:16 2021 +0200 @@ -9,6 +9,7 @@ import sys import re +import contextlib from enum import Enum @@ -1891,10 +1892,8 @@ self.dbs.remoteStatement( self.__debugUI.getSelectedDebuggerId(), cmd) while self.inCommandExecution: - try: + with contextlib.suppress(KeyboardInterrupt): QApplication.processEvents() - except KeyboardInterrupt: - pass else: if not self.__echoInput: cmd = self.buff
--- a/eric6/Sessions/SessionFile.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Sessions/SessionFile.py Wed Apr 14 19:59:16 2021 +0200 @@ -226,7 +226,7 @@ jsonString = json.dumps(sessionDict, indent=2) with open(filename, "w") as f: f.write(jsonString) - except (TypeError, EnvironmentError) as err: + except (TypeError, OSError) as err: with E5OverridenCursor(): E5MessageBox.critical( None, @@ -253,7 +253,7 @@ with open(filename, "r") as f: jsonString = f.read() sessionDict = json.loads(jsonString) - except (EnvironmentError, json.JSONDecodeError) as err: + except (OSError, json.JSONDecodeError) as err: E5MessageBox.critical( None, self.tr("Read Session"),
--- a/eric6/Snapshot/SnapWidget.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Snapshot/SnapWidget.py Wed Apr 14 19:59:16 2021 +0200 @@ -13,6 +13,7 @@ import os import re +import contextlib from PyQt5.QtCore import ( pyqtSlot, Qt, QFile, QFileInfo, QTimer, QPoint, QMimeData, QLocale, @@ -142,10 +143,8 @@ outputFormats = [] writeFormats = QImageWriter.supportedImageFormats() for writeFormat in writeFormats: - try: + with contextlib.suppress(KeyError): outputFormats.append(filters[bytes(writeFormat).decode()]) - except KeyError: - pass outputFormats.sort() self.__outputFilter = ';;'.join(outputFormats)
--- a/eric6/Snapshot/SnapshotWaylandGrabber.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Snapshot/SnapshotWaylandGrabber.py Wed Apr 14 19:59:16 2021 +0200 @@ -9,6 +9,7 @@ import os import uuid +import contextlib from PyQt5.QtCore import pyqtSignal, QObject, QTimer from PyQt5.QtGui import QPixmap, QCursor @@ -141,11 +142,8 @@ filename = reply.arguments()[0] if filename: snapshot = QPixmap(filename) - try: + with contextlib.suppress(OSError): os.remove(filename) - except OSError: - # just ignore it - pass elif Globals.isGnomeDesktop(): path = self.__temporaryFilename() interface = QDBusInterface( @@ -163,11 +161,8 @@ filename = reply.arguments()[1] if filename: snapshot = QPixmap(filename) - try: + with contextlib.suppress(OSError): os.remove(filename) - except OSError: - # just ignore it - pass self.grabbed.emit(snapshot) @@ -200,11 +195,8 @@ filename = reply.arguments()[0] if filename: snapshot = QPixmap(filename) - try: + with contextlib.suppress(OSError): os.remove(filename) - except OSError: - # just ignore it - pass elif Globals.isGnomeDesktop(): # Step 1: grab entire desktop path = self.__temporaryFilename() @@ -224,11 +216,8 @@ filename = reply.arguments()[1] if filename: snapshot = QPixmap(filename) - try: + with contextlib.suppress(OSError): os.remove(filename) - except OSError: - # just ignore it - pass # Step 2: extract the area of the screen containing # the cursor @@ -264,11 +253,8 @@ filename = reply.arguments()[0] if filename: snapshot = QPixmap(filename) - try: + with contextlib.suppress(OSError): os.remove(filename) - except OSError: - # just ignore it - pass elif Globals.isGnomeDesktop(): path = self.__temporaryFilename() interface = QDBusInterface( @@ -287,11 +273,8 @@ filename = reply.arguments()[1] if filename: snapshot = QPixmap(filename) - try: + with contextlib.suppress(OSError): os.remove(filename) - except OSError: - # just ignore it - pass self.grabbed.emit(snapshot) @@ -324,11 +307,8 @@ filename = reply.arguments()[1] if filename: snapshot = QPixmap(filename) - try: + with contextlib.suppress(OSError): os.remove(filename) - except OSError: - # just ignore it - pass self.grabbed.emit(snapshot)
--- a/eric6/Tasks/Task.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Tasks/Task.py Wed Apr 14 19:59:16 2021 +0200 @@ -9,6 +9,7 @@ import os import time +import contextlib from PyQt5.QtCore import Qt, QUuid from PyQt5.QtWidgets import QTreeWidgetItem @@ -144,13 +145,10 @@ nonBoldFont = self.font(0) nonBoldFont.setBold(False) for col in range(5): - try: + with contextlib.suppress(KeyError): self.setBackground( col, Preferences.getTasks( Task.TaskType2ColorName[self.taskType])) - except KeyError: - # do not set background color if type is not known - pass if self._isProjectTask: self.setFont(col, boldFont)
--- a/eric6/Tasks/TasksFile.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Tasks/TasksFile.py Wed Apr 14 19:59:16 2021 +0200 @@ -90,7 +90,7 @@ jsonString = json.dumps(tasksDict, indent=2) with open(filename, "w") as f: f.write(jsonString) - except (TypeError, EnvironmentError) as err: + except (TypeError, OSError) as err: with E5OverridenCursor(): E5MessageBox.critical( None, @@ -117,7 +117,7 @@ with open(filename, "r") as f: jsonString = f.read() tasksDict = json.loads(jsonString) - except (EnvironmentError, json.JSONDecodeError) as err: + except (OSError, json.JSONDecodeError) as err: E5MessageBox.critical( None, self.tr("Read Tasks"),
--- a/eric6/Templates/TemplatesFile.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Templates/TemplatesFile.py Wed Apr 14 19:59:16 2021 +0200 @@ -76,7 +76,7 @@ jsonString = json.dumps(templatesDict, indent=2) with open(filename, "w") as f: f.write(jsonString) - except (TypeError, EnvironmentError) as err: + except (TypeError, OSError) as err: with E5OverridenCursor(): E5MessageBox.critical( None, @@ -103,7 +103,7 @@ with open(filename, "r") as f: jsonString = f.read() templatesDict = json.loads(jsonString) - except (EnvironmentError, json.JSONDecodeError) as err: + except (OSError, json.JSONDecodeError) as err: E5MessageBox.critical( None, self.tr("Read Templates"),
--- a/eric6/Tools/TRPreviewer.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Tools/TRPreviewer.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import ( QDir, QTimer, QFileInfo, pyqtSignal, QEvent, QSize, QTranslator, QObject, @@ -723,10 +724,8 @@ del self.__widget self.__widget = None - try: + with contextlib.suppress(Exception): self.__widget = uic.loadUi(self.__uiFileName) - except Exception: # secok - pass if not self.__widget: E5MessageBox.warning(
--- a/eric6/Tools/UIPreviewer.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Tools/UIPreviewer.py Wed Apr 14 19:59:16 2021 +0200 @@ -7,6 +7,8 @@ Module implementing the UI Previewer main window. """ +import contextlib + from PyQt5.QtCore import QDir, QFileInfo, QEvent, QSize, Qt from PyQt5.QtGui import QKeySequence, QImageWriter, QPainter from PyQt5.QtWidgets import ( @@ -347,10 +349,8 @@ self.mainWidget = None # load the file - try: + with contextlib.suppress(Exception): self.mainWidget = uic.loadUi(fn) - except Exception: # secok - pass if self.mainWidget: self.currentFile = fn
--- a/eric6/UI/EmailDialog.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/UI/EmailDialog.py Wed Apr 14 19:59:16 2021 +0200 @@ -10,6 +10,7 @@ import os import mimetypes import smtplib +import contextlib from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtGui import QTextOption @@ -184,10 +185,8 @@ Private method to delete attached files. """ for f in self.__deleteFiles: - try: + with contextlib.suppress(OSError): os.remove(f) - except OSError: - pass def __encodedText(self, txt): """
--- a/eric6/UI/UserInterface.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/UI/UserInterface.py Wed Apr 14 19:59:16 2021 +0200 @@ -15,6 +15,7 @@ import datetime import getpass import functools +import contextlib from PyQt5.QtCore import ( pyqtSlot, QTimer, QFile, QFileInfo, pyqtSignal, PYQT_VERSION_STR, QDate, @@ -3961,13 +3962,11 @@ It must be one of "ui" or "wizards". """ for act in actions: - try: + with contextlib.suppress(ValueError): if actionType == 'ui': self.actions.remove(act) elif actionType == 'wizards': self.wizardsActions.remove(act) - except ValueError: - pass def getActions(self, actionType): """ @@ -6672,11 +6671,8 @@ fn = os.path.join(Utilities.getConfigDir(), f"eric6_crash_session{ext}") if os.path.exists(fn): - try: + with contextlib.suppress(OSError): os.remove(fn) - except OSError: - # ignore it silently - pass def __writeCrashSession(self): """
--- a/eric6/Utilities/BackgroundClient.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Utilities/BackgroundClient.py Wed Apr 14 19:59:16 2021 +0200 @@ -16,6 +16,7 @@ import sys import time import traceback +import contextlib from zlib import adler32 @@ -124,9 +125,8 @@ data = b'' self.connection.setblocking(False) try: - data = self.connection.recv(length, socket.MSG_PEEK) - except OSError: - pass + with contextlib.suppress(OSError): + data = self.connection.recv(length, socket.MSG_PEEK) finally: self.connection.setblocking(True)
--- a/eric6/Utilities/ModuleParser.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Utilities/ModuleParser.py Wed Apr 14 19:59:16 2021 +0200 @@ -18,6 +18,7 @@ import os import importlib.machinery import re +import contextlib import Utilities from functools import reduce @@ -1543,10 +1544,8 @@ _extensions = ['.py', '.pyw', '.ptl', '.rb'] else: _extensions = extensions[:] - try: + with contextlib.suppress(ValueError): _extensions.remove('.py') - except ValueError: - pass modname = module
--- a/eric6/Utilities/__init__.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/Utilities/__init__.py Wed Apr 14 19:59:16 2021 +0200 @@ -17,6 +17,7 @@ import ctypes import subprocess # secok import shlex +import contextlib def __showwarning(message, category, filename, lineno, file=None, line=""): @@ -655,11 +656,9 @@ # interpret as int first value = int(value) except ValueError: - try: + with contextlib.suppress(ValueError): # interpret as float next value = float(value) - except ValueError: - pass flags[key] = value else:
--- a/eric6/VCS/StatusMonitorThread.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/VCS/StatusMonitorThread.py Wed Apr 14 19:59:16 2021 +0200 @@ -7,6 +7,8 @@ Module implementing the VCS status monitor thread base class. """ +import contextlib + from PyQt5.QtCore import ( QThread, QMutex, QWaitCondition, pyqtSignal, QCoreApplication ) @@ -173,10 +175,8 @@ @param name name of the entry to be cleared (string) """ key = self.project.getRelativePath(name) - try: + with contextlib.suppress(KeyError): del self.reportedStates[key] - except KeyError: - pass def _performMonitor(self): """
--- a/eric6/VCS/VersionControl.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/VCS/VersionControl.py Wed Apr 14 19:59:16 2021 +0200 @@ -9,6 +9,7 @@ """ import os +import contextlib from PyQt5.QtCore import ( QObject, QThread, QMutex, QProcess, Qt, pyqtSignal, QCoreApplication @@ -521,10 +522,8 @@ """ if self.vcsSupportCommandOptions(): for key in options: - try: + with contextlib.suppress(KeyError): self.options[key] = options[key] - except KeyError: - pass def vcsGetOptions(self): """ @@ -545,10 +544,8 @@ @param data a dictionary of vcs specific data """ for key in data: - try: + with contextlib.suppress(KeyError): self.otherData[key] = data[key] - except KeyError: - pass def vcsGetOtherData(self): """
--- a/eric6/WebBrowser/FeaturePermissions/FeaturePermissionBar.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/WebBrowser/FeaturePermissions/FeaturePermissionBar.py Wed Apr 14 19:59:16 2021 +0200 @@ -7,6 +7,8 @@ Module implementing the feature permission bar widget. """ +import contextlib + from PyQt5.QtCore import pyqtSlot, QUrl from PyQt5.QtWidgets import QLabel, QHBoxLayout, QPushButton from PyQt5.QtWebEngineWidgets import QWebEnginePage @@ -120,11 +122,9 @@ self.__layout.addWidget(self.__denyButton) self.__layout.addWidget(self.__discardButton) - try: + with contextlib.suppress(KeyError): self.__iconLabel.setPixmap(UI.PixmapCache.getPixmap( self.__permissionFeatureIconNames[self.__feature])) - except KeyError: - pass try: self.__messageLabel.setText(
--- a/eric6/WebBrowser/GreaseMonkey/GreaseMonkeyManager.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/WebBrowser/GreaseMonkey/GreaseMonkeyManager.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import ( pyqtSignal, pyqtSlot, Qt, QObject, QTimer, QFile, QFileInfo, QDir, @@ -128,11 +129,8 @@ ) if deleteScript: - try: + with contextlib.suppress(OSError): os.remove(fileName) - except OSError: - # ignore - pass def scriptsDirectory(self): """ @@ -267,10 +265,8 @@ if not script: return False - try: + with contextlib.suppress(ValueError): self.__scripts.remove(script) - except ValueError: - pass fullName = script.fullName() collection = WebBrowserWindow.webProfile().scripts()
--- a/eric6/WebBrowser/OpenSearch/OpenSearchManager.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/WebBrowser/OpenSearch/OpenSearchManager.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import ( pyqtSignal, QObject, QUrl, QFile, QDir, QIODevice, QUrlQuery @@ -547,10 +548,8 @@ return if engine is None: - try: + with contextlib.suppress(KeyError): del self.__keywords[keyword] - except KeyError: - pass else: self.__keywords[keyword] = engine
--- a/eric6/WebBrowser/SafeBrowsing/SafeBrowsingUrl.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/WebBrowser/SafeBrowsing/SafeBrowsingUrl.py Wed Apr 14 19:59:16 2021 +0200 @@ -13,6 +13,7 @@ import struct import hashlib import urllib.parse +import contextlib import Preferences @@ -107,15 +108,11 @@ host = host.strip('.') host = re.sub(r'\.+', '.', host).lower() if host.isdigit(): - try: + with contextlib.suppress(Exception): host = socket.inet_ntoa(struct.pack("!I", int(host))) - except Exception: # secok - pass if host.startswith('0x') and '.' not in host: - try: + with contextlib.suppress(Exception): host = socket.inet_ntoa(struct.pack("!I", int(host, 16))) - except Exception: # secok - pass quotedPath = quote(path) quotedHost = quote(host) if port is not None:
--- a/eric6/WebBrowser/SpellCheck/ManageDictionariesDialog.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/WebBrowser/SpellCheck/ManageDictionariesDialog.py Wed Apr 14 19:59:16 2021 +0200 @@ -12,6 +12,7 @@ import zipfile import glob import shutil +import contextlib from PyQt5.QtCore import pyqtSlot, Qt, QUrl from PyQt5.QtWidgets import ( @@ -424,11 +425,8 @@ locales = itm.data(ManageDictionariesDialog.LocalesRole) for locale in locales: bdic = os.path.join(installLocation, locale + ".bdic") - try: + with contextlib.suppress(OSError): os.remove(bdic) - except OSError: - # ignore silently - pass self.dictionariesList.clearSelection()
--- a/eric6/WebBrowser/Sync/SyncManager.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/WebBrowser/Sync/SyncManager.py Wed Apr 14 19:59:16 2021 +0200 @@ -7,6 +7,8 @@ Module implementing the synchronization manager class. """ +import contextlib + from PyQt5.QtCore import QObject, pyqtSignal import Preferences @@ -102,13 +104,11 @@ .bookmarksSaved.connect(self.__syncBookmarks) ) else: - try: + with contextlib.suppress(TypeError): ( WebBrowserWindow.bookmarksManager() .bookmarksSaved.disconnect(self.__syncBookmarks) ) - except TypeError: - pass # connect sync manager to history manager if Preferences.getWebBrowser("SyncHistory"): @@ -117,13 +117,11 @@ .connect(self.__syncHistory) ) else: - try: + with contextlib.suppress(TypeError): ( WebBrowserWindow.historyManager() .historySaved.disconnect(self.__syncHistory) ) - except TypeError: - pass # connect sync manager to passwords manager if Preferences.getWebBrowser("SyncPasswords"): @@ -132,13 +130,11 @@ .passwordsSaved.connect(self.__syncPasswords) ) else: - try: + with contextlib.suppress(TypeError): ( WebBrowserWindow.passwordManager() .passwordsSaved.disconnect(self.__syncPasswords) ) - except TypeError: - pass # connect sync manager to user agent manager if Preferences.getWebBrowser("SyncUserAgents"): @@ -147,14 +143,12 @@ .userAgentSettingsSaved.connect(self.__syncUserAgents) ) else: - try: + with contextlib.suppress(TypeError): ( WebBrowserWindow.userAgentsManager() .userAgentSettingsSaved.disconnect( self.__syncUserAgents) ) - except TypeError: - pass # connect sync manager to speed dial if Preferences.getWebBrowser("SyncSpeedDial"): @@ -163,49 +157,37 @@ .speedDialSaved.connect(self.__syncSpeedDial) ) else: - try: + with contextlib.suppress(TypeError): ( WebBrowserWindow.speedDial() .speedDialSaved.disconnect(self.__syncSpeedDial) ) - except TypeError: - pass else: self.__handler = None - try: + with contextlib.suppress(TypeError): ( WebBrowserWindow.bookmarksManager() .bookmarksSaved.disconnect(self.__syncBookmarks) ) - except TypeError: - pass - try: + with contextlib.suppress(TypeError): ( WebBrowserWindow.historyManager().historySaved .disconnect(self.__syncHistory) ) - except TypeError: - pass - try: + with contextlib.suppress(TypeError): ( WebBrowserWindow.passwordManager() .passwordsSaved.disconnect(self.__syncPasswords) ) - except TypeError: - pass - try: + with contextlib.suppress(TypeError): ( WebBrowserWindow.userAgentsManager() .userAgentSettingsSaved.disconnect(self.__syncUserAgents) ) - except TypeError: - pass - try: + with contextlib.suppress(TypeError): WebBrowserWindow.speedDial().speedDialSaved.disconnect( self.__syncSpeedDial) - except TypeError: - pass def syncEnabled(self): """
--- a/eric6/WebBrowser/Tools/WebIconProvider.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/WebBrowser/Tools/WebIconProvider.py Wed Apr 14 19:59:16 2021 +0200 @@ -9,6 +9,7 @@ import json import os +import contextlib from PyQt5.QtCore import ( pyqtSignal, QObject, QByteArray, QBuffer, QIODevice, QUrl @@ -120,12 +121,8 @@ filename = os.path.join(self.__iconDatabasePath, self.__iconsFileName) - try: - with open(filename, "w") as f: - json.dump(db, f) - except OSError: - # ignore silentyl - pass + with contextlib.suppress(OSError), open(filename, "w") as f: + json.dump(db, f) def saveIcon(self, view): """
--- a/eric6/eric6.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/eric6.py Wed Apr 14 19:59:16 2021 +0200 @@ -37,6 +37,7 @@ import time import logging import io +import contextlib try: from PyQt5.QtCore import qWarning, QLibraryInfo, QTimer, QCoreApplication @@ -51,10 +52,8 @@ " it is installed and accessible.") sys.exit(100) -try: +with contextlib.suppress(ImportError): from PyQt5 import QtWebEngineWidgets # __IGNORE_WARNING__ -except ImportError: - pass # some global variables needed to start the application args = None @@ -201,12 +200,10 @@ sections = ['', separator, timeString, separator, errmsg, separator, tbinfo] msg = '\n'.join(sections) - try: - with open(logFile, "w", encoding="utf-8") as f: - f.write(msg) - f.write(versionInfo) - except OSError: - pass + with contextlib.suppress(OSError), \ + open(logFile, "w", encoding="utf-8") as f: + f.write(msg) + f.write(versionInfo) if inMainLoop is None: warning = notice + msg + versionInfo
--- a/eric6/eric6config.py Wed Apr 14 19:38:19 2021 +0200 +++ b/eric6/eric6config.py Wed Apr 14 19:59:16 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib __ericDir = os.path.dirname(__file__) @@ -38,10 +39,8 @@ @return requested config value @exception AttributeError raised to indicate an invalid config entry """ - try: + with contextlib.suppress(KeyError): return _pkg_config[name] - except KeyError: - pass raise AttributeError( '"{0}" is not a valid configuration value'.format(name))
--- a/scripts/install.py Wed Apr 14 19:38:19 2021 +0200 +++ b/scripts/install.py Wed Apr 14 19:59:16 2021 +0200 @@ -24,6 +24,7 @@ import shlex import datetime import getpass +import contextlib # Define the globals. progName = None @@ -1744,10 +1745,8 @@ if not fileName: return - try: + with contextlib.suppress(OSError): os.rename(fileName, fileName + ".orig") - except OSError: - pass try: hgOut = subprocess.check_output(["hg", "identify", "-i"]) # secok hgOut = hgOut.decode() @@ -2059,24 +2058,20 @@ json.dump(installInfo, installInfoFile, indent=2) # do some cleanup - try: + with contextlib.suppress(OSError): if installFromSource: os.remove(configName) configNameC = configName + 'c' if os.path.exists(configNameC): os.remove(configNameC) os.rename(configName + ".orig", configName) - except OSError: - pass - try: + with contextlib.suppress(OSError): if installFromSource and infoName: os.remove(infoName) infoNameC = infoName + 'c' if os.path.exists(infoNameC): os.remove(infoNameC) os.rename(infoName + ".orig", infoName) - except OSError: - pass print("\nInstallation complete.") print()
--- a/setup.py Wed Apr 14 19:38:19 2021 +0200 +++ b/setup.py Wed Apr 14 19:59:16 2021 +0200 @@ -15,6 +15,7 @@ import fnmatch import datetime import json +import contextlib from setuptools import setup, find_packages @@ -135,10 +136,8 @@ if not fileName: return - try: + with contextlib.suppress(OSError): os.rename(fileName, fileName + ".orig") - except OSError: - pass try: hgOut = subprocess.check_output(["hg", "identify", "-i"]) # secok hgOut = hgOut.decode() @@ -170,10 +169,8 @@ if not fileName: return - try: + with contextlib.suppress(OSError): os.rename(fileName, fileName + ".orig") - except OSError: - pass with open(fileName + ".orig", "r", encoding="utf-8") as f: text = f.read() text = (