Thu, 15 Apr 2021 18:11:24 +0200
Applied some more code simplifications suggested by the new Simplify checker (Y105: use contextlib.suppress) (batch 2).
--- a/eric6/CondaInterface/Conda.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/CondaInterface/Conda.py Thu Apr 15 18:11:24 2021 +0200 @@ -9,6 +9,7 @@ import json import os +import contextlib from PyQt5.QtCore import pyqtSignal, QObject, QProcess, QCoreApplication from PyQt5.QtWidgets import QDialog @@ -589,12 +590,9 @@ output = str(proc.readAllStandardOutput(), Preferences.getSystem("IOEncoding"), 'replace').strip() - try: + with contextlib.suppress(Exception): packages = json.loads(output) ok = "error" not in packages - except Exception: # secok - # return values for errors is already set - pass return ok, packages
--- a/eric6/DebugClients/Python/AsyncFile.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/DebugClients/Python/AsyncFile.py Thu Apr 15 18:11:24 2021 +0200 @@ -10,6 +10,7 @@ import socket import threading +import contextlib from DebugUtilities import prepareJsonCommand @@ -109,10 +110,9 @@ break try: - try: + with contextlib.suppress(UnicodeEncodeError, + UnicodeDecodeError): buf = buf.encode('utf-8', 'backslashreplace') - except (UnicodeEncodeError, UnicodeDecodeError): - pass self.sock.sendall(buf) self.nWriteErrors = 0 except OSError:
--- a/eric6/DebugClients/Python/BreakpointWatch.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/DebugClients/Python/BreakpointWatch.py Thu Apr 15 18:11:24 2021 +0200 @@ -61,13 +61,11 @@ """ Public method to clear this breakpoint. """ - try: + with contextlib.suppress(KeyError): del Breakpoint.breaks[(self.file, self.line)] Breakpoint.breakInFile[self.file].remove(self.line) if not Breakpoint.breakInFile[self.file]: del Breakpoint.breakInFile[self.file] - except KeyError: - pass def enable(self): """
--- a/eric6/DebugClients/Python/DebugClientBase.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/DebugClients/Python/DebugClientBase.py Thu Apr 15 18:11:24 2021 +0200 @@ -1942,12 +1942,10 @@ pos -= 1 # Get local and global completions - try: + with contextlib.suppress(AttributeError): localdict = self.currentThread.getFrameLocals(self.framenr) localCompleter = Completer(localdict).complete self.__getCompletionList(text, localCompleter, completions) - except AttributeError: - pass cf = self.currentThread.getCurrentFrame() frmnr = self.framenr
--- a/eric6/DebugClients/Python/DebugVariables.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/DebugClients/Python/DebugVariables.py Thu Apr 15 18:11:24 2021 +0200 @@ -52,11 +52,9 @@ d = {} for name in names: - try: + with contextlib.suppress(Exception): attribute = getattr(var, name) d[name] = attribute - except Exception: # secok - pass # if we can't get it, simply ignore it return d @@ -86,11 +84,9 @@ d = {} for name in names: - try: + with contextlib.suppress(Exception): attribute = getattr(var, name) d[name] = attribute - except Exception: # secok - pass # if we can't get it, simply ignore it yield -1, d while True: @@ -658,32 +654,28 @@ with contextlib.suppress(Exception): _TypeMap.append((long, None)) # __IGNORE_WARNING__ - try: + with contextlib.suppress(ImportError): import array _TypeMap.append((array.array, arrayResolver)) - except ImportError: - pass # array.array may not be available + # array.array may not be available - try: + with contextlib.suppress(ImportError): import numpy _TypeMap.append((numpy.ndarray, ndarrayResolver)) - except ImportError: - pass # numpy may not be installed + # numpy may not be installed - try: + with contextlib.suppress(ImportError): from django.utils.datastructures import MultiValueDict # it should go before dict _TypeMap.insert(0, (MultiValueDict, multiValueDictResolver)) - except ImportError: - pass # django may not be installed + # django may not be installed - try: + with contextlib.suppress(ImportError): from collections.abc import ItemsView, KeysView, ValuesView _TypeMap.append((ItemsView, dictViewResolver)) _TypeMap.append((KeysView, dictViewResolver)) _TypeMap.append((ValuesView, dictViewResolver)) - except ImportError: - pass # not available on all Python versions + # not available on all Python versions def getType(obj):
--- a/eric6/DebugClients/Python/MultiProcessDebugExtension.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/DebugClients/Python/MultiProcessDebugExtension.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ support multiprocess debugging. """ +import contextlib from DebugUtilities import ( patchArguments, patchArgumentStringWindows, isPythonProgram, @@ -404,10 +405,8 @@ patchModule(_subprocess, 'CreateProcess', createCreateProcess) else: patchModule(os, "fork", createFork) - try: + with contextlib.suppress(ImportError): import _posixsubprocess patchModule(_posixsubprocess, "fork_exec", createForkExec) - except ImportError: - pass _debugClient = debugClient
--- a/eric6/DebugClients/Python/PyProfile.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/DebugClients/Python/PyProfile.py Thu Apr 15 18:11:24 2021 +0200 @@ -52,13 +52,11 @@ if not os.path.exists(self.timingCache): return - try: - with open(self.timingCache, 'rb') as cache: - timings = marshal.load(cache) # secok - if isinstance(timings, dict): - self.timings = timings - except (OSError, EOFError, ValueError, TypeError): - pass + with contextlib.suppress(OSError, EOFError, ValueError, TypeError), \ + open(self.timingCache, 'rb') as cache: + timings = marshal.load(cache) # secok + if isinstance(timings, dict): + self.timings = timings def save(self): """ @@ -79,11 +77,9 @@ @param file name of the file to write to (string) """ self.create_stats() - try: - with open(file, 'wb') as f: - pickle.dump(self.stats, f, 4) - except (OSError, pickle.PickleError): - pass + with contextlib.suppress(OSError, pickle.PickleError), \ + open(file, 'wb') as f: + pickle.dump(self.stats, f, 4) def erase(self): """
--- a/eric6/Debugger/DebugServer.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Debugger/DebugServer.py Thu Apr 15 18:11:24 2021 +0200 @@ -1487,11 +1487,8 @@ @param debuggerId ID of the debugger backend @type str """ - try: + with contextlib.suppress(AttributeError): self.debuggerInterface.remoteClientDisassembly(debuggerId) - except AttributeError: - # remote client doesn't support that - pass def remoteClientSetFilter(self, debuggerId, scope, filterStr): """ @@ -1996,12 +1993,9 @@ @param venvName name of the virtual environment @type str """ - try: + with contextlib.suppress(KeyError): self.__debuggerInterfaceRegistry[clientType][0] = capabilities self.clientCapabilities.emit(capabilities, clientType, venvName) - except KeyError: - # ignore silently - pass def signalClientCompletionList(self, completionList, text, debuggerId): """
--- a/eric6/Debugger/DebugUI.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Debugger/DebugUI.py Thu Apr 15 18:11:24 2021 +0200 @@ -9,6 +9,7 @@ import os import copy +import contextlib from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject, Qt from PyQt5.QtGui import QKeySequence @@ -1235,22 +1236,18 @@ ): res = None if stackTrace: - try: + with contextlib.suppress(UnicodeError, OSError): file, line = stackTrace[0][:2] source, encoding = Utilities.readEncodedFile(file) source = source.splitlines(True) if len(source) >= line: lineFlags = Utilities.extractLineFlags( source[line - 1].strip()) - try: + with contextlib.suppress(IndexError): lineFlags += Utilities.extractLineFlags( source[line].strip(), flagsLine=True) - except IndexError: - pass if "__IGNORE_EXCEPTION__" in lineFlags: res = E5MessageBox.No - except (UnicodeError, OSError): - pass if res != E5MessageBox.No: self.viewmanager.setFileLine( stackTrace[0][0], stackTrace[0][1], True)
--- a/eric6/Debugger/DebuggerInterfacePython.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Debugger/DebuggerInterfacePython.py Thu Apr 15 18:11:24 2021 +0200 @@ -279,11 +279,9 @@ envlist = shlex.split( Preferences.getDebugger("DebugEnvironment")) for el in envlist: - try: + with contextlib.suppress(ValueError): key, value = el.split('=', 1) clientEnv[str(key)] = str(value) - except ValueError: - pass if execPath: if "PATH" in clientEnv: clientEnv["PATH"] = os.pathsep.join( @@ -462,11 +460,9 @@ envlist = shlex.split( project.getDebugProperty("ENVIRONMENTSTRING")) for el in envlist: - try: + with contextlib.suppress(ValueError): key, value = el.split('=', 1) clientEnv[str(key)] = str(value) - except ValueError: - pass if execPath: if "PATH" in clientEnv: clientEnv["PATH"] = os.pathsep.join(
--- a/eric6/Debugger/ExceptionLogger.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Debugger/ExceptionLogger.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing the Exception Logger widget. """ +import contextlib + from PyQt5.QtCore import pyqtSignal, Qt from PyQt5.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu @@ -141,11 +143,9 @@ entry = itm.text(0) entryList = entry.split(",") - try: + with contextlib.suppress(IndexError, ValueError): self.sourceFile.emit(entryList[0], int(entryList[1])) - except (IndexError, ValueError): - pass - + def __configure(self): """ Private method to open the configuration dialog.
--- a/eric6/DocumentationTools/ModuleDocumentor.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/DocumentationTools/ModuleDocumentor.py Thu Apr 15 18:11:24 2021 +0200 @@ -13,6 +13,7 @@ import sys import re +import contextlib from Utilities import html_uencode from Utilities.ModuleParser import RB_SOURCE, Function @@ -466,7 +467,7 @@ """ lst = [] if includeInit: - try: + with contextlib.suppress(KeyError): lst.append(self.listEntryTemplate.format( **{'Link': "{0}.{1}".format(className, '__init__'), 'Name': clsName, @@ -479,8 +480,6 @@ self.keywords.append( ("{0} (Constructor)".format(className), "#{0}.{1}".format(className, '__init__'))) - except KeyError: - pass for name in names: lst.append(self.listEntryTemplate.format(
--- a/eric6/E5Gui/E5ErrorMessage.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/E5Gui/E5ErrorMessage.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a specialized error message dialog. """ +import contextlib + from PyQt5.QtCore import ( qInstallMessageHandler, QtDebugMsg, QtWarningMsg, QtCriticalMsg, QtFatalMsg, QThread, QMetaObject, Qt, Q_ARG, QSettings @@ -118,7 +120,7 @@ # just ignore the message return - try: + with contextlib.suppress(RuntimeError): if msgType == QtDebugMsg: messageType = "Debug Message:" elif msgType == QtWarningMsg: @@ -154,8 +156,6 @@ Qt.ConnectionType.QueuedConnection, Q_ARG(str, msg)) return - except RuntimeError: - pass elif _origMsgHandler: _origMsgHandler(msgType, message) return
--- a/eric6/E5Gui/E5TabWidget.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/E5Gui/E5TabWidget.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a TabWidget class substituting QTabWidget. """ +import contextlib + from PyQt5.QtCore import pyqtSignal, Qt, QPoint, QMimeData from PyQt5.QtGui import QDrag from PyQt5.QtWidgets import QTabWidget, QTabBar, QApplication, QStyle @@ -34,7 +36,7 @@ @param event reference to the wheel event (QWheelEvent) """ - try: + with contextlib.suppress(AttributeError): delta = event.angleDelta().y() if delta > 0: self._tabWidget.prevTab() @@ -42,8 +44,6 @@ self._tabWidget.nextTab() event.accept() - except AttributeError: - pass class E5DnDTabBar(E5WheelTabBar):
--- a/eric6/E5Network/E5GoogleMail.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/E5Network/E5GoogleMail.py Thu Apr 15 18:11:24 2021 +0200 @@ -11,6 +11,7 @@ import base64 import json import datetime +import contextlib from googleapiclient import discovery from google.oauth2.credentials import Credentials @@ -182,12 +183,10 @@ prompt="select_account" ) if self.__browser is None: - try: + with contextlib.suppress(ImportError): self.__browser = E5GoogleMailAuthBrowser() self.__browser.approvalCodeReceived.connect( self.__processAuthorization) - except ImportError: - pass if self.__browser: self.__browser.show() self.__browser.load(QUrl(authorizationUrl))
--- a/eric6/E5Network/E5SslCertificateSelectionDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/E5Network/E5SslCertificateSelectionDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -114,7 +114,7 @@ """ Private slot to show data of the selected certificate. """ - try: + with contextlib.suppress(ImportError): from E5Network.E5SslCertificatesInfoDialog import ( E5SslCertificatesInfoDialog ) @@ -123,8 +123,6 @@ 0, self.CertRole)) dlg = E5SslCertificatesInfoDialog(cert, self) dlg.exec() - except ImportError: - pass def getSelectedCertificate(self): """
--- a/eric6/E5Network/E5SslCertificatesDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/E5Network/E5SslCertificatesDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -131,7 +131,7 @@ """ Private slot to show data of the selected server certificate. """ - try: + with contextlib.suppress(ImportError): from E5Network.E5SslCertificatesInfoDialog import ( E5SslCertificatesInfoDialog ) @@ -140,8 +140,6 @@ 0, self.CertRole)) dlg = E5SslCertificatesInfoDialog(cert, self) dlg.exec() - except ImportError: - pass @pyqtSlot() def on_serversDeleteButton_clicked(self): @@ -339,7 +337,7 @@ """ Private slot to show data of the selected CA certificate. """ - try: + with contextlib.suppress(ImportError): from E5Network.E5SslCertificatesInfoDialog import ( E5SslCertificatesInfoDialog ) @@ -347,8 +345,6 @@ self.caCertificatesTree.currentItem().data(0, self.CertRole)) dlg = E5SslCertificatesInfoDialog(cert, self) dlg.exec() - except ImportError: - pass @pyqtSlot() def on_caDeleteButton_clicked(self):
--- a/eric6/E5Network/E5SslErrorHandler.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/E5Network/E5SslErrorHandler.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import platform +import contextlib from PyQt5.QtCore import QObject, QByteArray from PyQt5.QtNetwork import ( @@ -64,11 +65,9 @@ except AttributeError: sslProtocol = QSsl.SslProtocol.SecureProtocols sslCfg.setProtocol(sslProtocol) - try: + with contextlib.suppress(AttributeError): sslCfg.setSslOption(QSsl.SslOption.SslOptionDisableCompression, True) - except AttributeError: - pass QSslConfiguration.setDefaultConfiguration(sslCfg) def sslErrorsReplySlot(self, reply, errors): @@ -177,12 +176,10 @@ sslCfg.setProtocol(QSsl.SslProtocol.TlsV1_1OrLater) except AttributeError: sslCfg.setProtocol(QSsl.SslProtocol.SecureProtocols) - try: + with contextlib.suppress(AttributeError): sslCfg.setSslOption( QSsl.SslOption.SslOptionDisableCompression, True) - except AttributeError: - pass QSslConfiguration.setDefaultConfiguration(sslCfg) certificateDict = {}
--- a/eric6/Globals/__init__.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Globals/__init__.py Thu Apr 15 18:11:24 2021 +0200 @@ -322,13 +322,11 @@ # step 2: try the qt5_applications package if not path: - try: + with contextlib.suppress(ImportError): import qt5_applications path = os.path.join(os.path.dirname(qt5_applications.__file__), "Qt", "bin") - except ImportError: - # qt5-applications is not installed; just go to the next step - pass + # if qt5-applications is not installed just go to the next step # step 3: determine from used Python interpreter (designer is test object) if not path:
--- a/eric6/Graphics/UMLItem.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Graphics/UMLItem.py Thu Apr 15 18:11:24 2021 +0200 @@ -84,12 +84,8 @@ self.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsMovable, True) self.setFlag(QGraphicsItem.GraphicsItemFlag.ItemIsSelectable, True) - try: - self.setFlag( - QGraphicsItem.GraphicsItemFlag.ItemSendsGeometryChanges, True) - except AttributeError: - # only available for Qt 4.6.0 and newer - pass + self.setFlag( + QGraphicsItem.GraphicsItemFlag.ItemSendsGeometryChanges, True) def getName(self): """
--- a/eric6/MicroPython/MicroPythonGraphWidget.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/MicroPython/MicroPythonGraphWidget.py Thu Apr 15 18:11:24 2021 +0200 @@ -12,6 +12,7 @@ import os import time import csv +import contextlib from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt from PyQt5.QtGui import QPainter @@ -180,13 +181,10 @@ rawValues = [val.strip() for val in line[1:-1].split(b",")] values = [] for raw in rawValues: - try: + with contextlib.suppress(ValueError): values.append(int(raw)) # ok, it is an integer continue - except ValueError: - # test for a float - pass try: values.append(float(raw)) except ValueError:
--- a/eric6/MicroPython/UF2FlashDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/MicroPython/UF2FlashDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -9,6 +9,7 @@ import os import shutil +import contextlib from PyQt5.QtCore import pyqtSlot, Qt, QCoreApplication, QThread, QEventLoop from PyQt5.QtWidgets import QDialog @@ -479,7 +480,7 @@ # second run for boards needing special treatment (e.g. RP2040) for board in SupportedUF2Boards: if not boardType or (board == boardType): - try: + with contextlib.suppress(KeyError): # find mounted volume volumes = SupportedUF2Boards[board]["volumes"][(0, 0)] foundVolumes = [] @@ -492,9 +493,6 @@ "UF2FlashDialog", "'{0}' Board").format(board), (0, 0), # VID/PID of (0, 0) is special )) - except KeyError: - # no special treatment required, carry on - pass return foundDevices
--- a/eric6/PluginManager/PluginInstallDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/PluginManager/PluginInstallDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -569,7 +569,7 @@ packageDir = os.path.join(destination, packageName) pluginFile = os.path.join(destination, pluginFileName) - try: + with contextlib.suppress(OSError, os.error): if packageDir and os.path.exists(packageDir): shutil.rmtree(packageDir) @@ -596,9 +596,6 @@ os.remove(fnamec) os.remove(pluginFile) - except (OSError, os.error): - # ignore some exceptions - pass class PluginInstallDialog(QDialog):
--- a/eric6/PluginManager/PluginManager.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/PluginManager/PluginManager.py Thu Apr 15 18:11:24 2021 +0200 @@ -161,11 +161,8 @@ self.__networkManager.sslErrors.connect(self.__sslErrors) self.__replies = [] - try: + with contextlib.suppress(AttributeError): self.__ui.onlineStateChanged.connect(self.__onlineStateChanged) - except AttributeError: - # it was not called from eric - pass def finalizeSetup(self): """ @@ -429,12 +426,10 @@ if reload_: importlib.reload(module) self.initOnDemandPlugin(name) - try: + with contextlib.suppress(KeyError, AttributeError): pluginObject = self.__onDemandInactivePlugins[name] pluginObject.initToolbar( self.__ui, e5App().getObject("ToolbarManager")) - except (KeyError, AttributeError): - pass except PluginLoadError: print("Error loading plug-in module:", name) except Exception as err: @@ -460,26 +455,18 @@ self.deactivatePlugin(name) if name in self.__inactiveModules: - try: + with contextlib.suppress(KeyError): pluginObject = self.__inactivePlugins[name] - try: + with contextlib.suppress(AttributeError): pluginObject.prepareUnload() - except AttributeError: - pass del self.__inactivePlugins[name] - except KeyError: - pass del self.__inactiveModules[name] elif name in self.__onDemandInactiveModules: - try: + with contextlib.suppress(KeyError): pluginObject = self.__onDemandInactivePlugins[name] - try: + with contextlib.suppress(AttributeError): pluginObject.prepareUnload() - except AttributeError: - pass del self.__onDemandInactivePlugins[name] - except KeyError: - pass del self.__onDemandInactiveModules[name] elif name in self.__failedModules: del self.__failedModules[name] @@ -562,11 +549,8 @@ """ self.initOnDemandPlugins() for pluginObject in self.__onDemandInactivePlugins.values(): - try: + with contextlib.suppress(AttributeError): pluginObject.initToolbar(self.__ui, toolbarManager) - except AttributeError: - # ignore it - pass def activatePlugins(self): """
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleChecker.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleChecker.py Thu Apr 15 18:11:24 2021 +0200 @@ -11,6 +11,7 @@ import ast import sys import multiprocessing +import contextlib import pycodestyle from Naming.NamingStyleChecker import NamingStyleChecker @@ -287,7 +288,11 @@ src = "".join(source) try: - tree = ast.parse(src, filename, 'exec') + if sys.version_info >= (3, 8): + # need the 'type_comments' parameter to include type annotations + tree = ast.parse(src, filename, 'exec', type_comments=True) + else: + tree = ast.parse(src, filename, 'exec') return None, None, tree except (SyntaxError, TypeError): exc_type, exc = sys.exc_info()[:2] @@ -479,11 +484,9 @@ if source: code = error["code"] lineFlags = extractLineFlags(source[lineno - 1].strip()) - try: + with contextlib.suppress(IndexError): lineFlags += extractLineFlags(source[lineno].strip(), flagsLine=True) - except IndexError: - pass if securityOk(code, lineFlags): error["securityOk"] = True
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleFixer.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/CodeStyleFixer.py Thu Apr 15 18:11:24 2021 +0200 @@ -394,13 +394,11 @@ """ sio = StringIO("".join(self.__source)) indentWord = " " # default in case of failure - try: + with contextlib.suppress(SyntaxError, tokenize.TokenError): for token in tokenize.generate_tokens(sio.readline): if token[0] == tokenize.INDENT: indentWord = token[1] break - except (SyntaxError, tokenize.TokenError): - pass return indentWord def __getIndent(self, line): @@ -427,7 +425,7 @@ self.__multiLineNumbers = set() self.__docLineNumbers = set() previousTokenType = '' - try: + with contextlib.suppress(SyntaxError, tokenize.TokenError): for t in tokenize.generate_tokens(sio.readline): tokenType = t[0] startRow = t[2][0] @@ -442,8 +440,6 @@ range(startRow, 1 + endRow)) previousTokenType = tokenType - except (SyntaxError, tokenize.TokenError): - pass return self.__multiLineNumbers, self.__docLineNumbers
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/DocStyle/DocStyleChecker.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/DocStyle/DocStyleChecker.py Thu Apr 15 18:11:24 2021 +0200 @@ -15,6 +15,7 @@ import tokenize import ast from io import StringIO +import contextlib try: ast.AsyncFunctionDef # __IGNORE_EXCEPTION__ @@ -464,7 +465,7 @@ tokenGenerator = tokenize.generate_tokens( StringIO(context.ssource()).readline) - try: + with contextlib.suppress(StopIteration): kind = None while kind != tokenize.INDENT: kind, _, _, _, _ = next(tokenGenerator) @@ -472,8 +473,6 @@ if kind == tokenize.STRING: # STRING after INDENT is a docstring return DocStyleContext( value, context.start() + line - 1, "docstring") - except StopIteration: - pass return None @@ -559,7 +558,7 @@ tokenGenerator = tokenize.generate_tokens( StringIO(classContext.ssource()).readline) kind, value, char = None, None, None - try: + with contextlib.suppress(StopIteration): while True: start, end = None, None while not (kind == tokenize.NAME and value == 'def'): @@ -588,8 +587,6 @@ ): context.setSpecial("classmethod") contexts.append(context) - except StopIteration: - pass self.__methodsCache = contexts return self.__methodsCache
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Miscellaneous/MiscellaneousChecker.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Miscellaneous/MiscellaneousChecker.py Thu Apr 15 18:11:24 2021 +0200 @@ -15,6 +15,7 @@ from collections import defaultdict import tokenize import copy +import contextlib import AstUtilities @@ -611,10 +612,8 @@ Private method to check, if built-ins are shadowed. """ functionDefs = [ast.FunctionDef] - try: + with contextlib.suppress(AttributeError): functionDefs.append(ast.AsyncFunctionDef) - except AttributeError: - pass ignoreBuiltinAssignments = self.__args.get( "BuiltinsChecker", @@ -799,19 +798,15 @@ "frozenset", ) functionDefs = [ast.FunctionDef] - try: + with contextlib.suppress(AttributeError): functionDefs.append(ast.AsyncFunctionDef) - except AttributeError: - pass for node in ast.walk(self.__tree): if any(isinstance(node, functionDef) for functionDef in functionDefs): defaults = node.args.defaults[:] - try: + with contextlib.suppress(AttributeError): defaults += node.args.kw_defaults[:] - except AttributeError: - pass for default in defaults: if any(isinstance(default, mutableType) for mutableType in mutableTypes): @@ -1161,14 +1156,12 @@ @return logging level @rtype str or None """ - try: + with contextlib.suppress(AttributeError): if node.func.value.id == "warnings": return None if node.func.attr in LoggingVisitor.LoggingLevels: return node.func.attr - except AttributeError: - pass return None @@ -1350,7 +1343,7 @@ else: self.__checkForM502(node) else: - try: + with contextlib.suppress(AttributeError, IndexError): # bad super() call if isinstance(node.func, ast.Name) and node.func.id == "super": args = node.args @@ -1381,8 +1374,6 @@ AstUtilities.isString(node.args[1]) ): self.violations.append((node, "M513")) - except (AttributeError, IndexError): - pass self.generic_visit(node)
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/PathLib/PathlibChecker.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/PathLib/PathlibChecker.py Thu Apr 15 18:11:24 2021 +0200 @@ -10,6 +10,7 @@ import ast import copy +import contextlib class PathlibChecker: @@ -177,12 +178,9 @@ @param name resolved name of the node @type str """ - try: + with contextlib.suppress(KeyError): errorCode = self.Function2Code[name] self.__error(node.lineno - 1, node.col_offset, errorCode) - except KeyError: - # name is not in our list of replacements - pass class PathlibVisitor(ast.NodeVisitor): @@ -260,12 +258,10 @@ @return resolved name @rtype str """ - try: + with contextlib.suppress(KeyError, IndexError): attr = self.__importAlias[self.__names[-1]] self.__names[-1] = attr - except (KeyError, IndexError): # do nothing if there is no such name or the names list is empty - pass return ".".join(reversed(self.__names))
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/SecurityUtils.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/Security/SecurityUtils.py Thu Apr 15 18:11:24 2021 +0200 @@ -9,6 +9,7 @@ import ast import os +import contextlib import AstUtilities @@ -154,16 +155,14 @@ """ prefix = "" if isinstance(node, ast.Attribute): - try: + with contextlib.suppress(Exception): val = 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 + # Id we can't get the fully qualified name for an attr, just return # its base name. - pass return "{0}.{1}".format(prefix, node.attr) else:
--- a/eric6/Plugins/CheckerPlugins/CodeStyleChecker/translations.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/CodeStyleChecker/translations.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import re +import contextlib from PyQt5.QtCore import QCoreApplication @@ -561,9 +562,9 @@ else: args = messageArgs - try: + with contextlib.suppress(KeyError): catalog = messageCatalogs[messageCategory] - try: + with contextlib.suppress(KeyError): message = catalog[messageCode] if args is None: return message @@ -572,10 +573,6 @@ return message(args) else: return message.format(*args) - except KeyError: - pass - except KeyError: - pass if example: return None
--- a/eric6/Plugins/CheckerPlugins/SyntaxChecker/SyntaxCheck.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/CheckerPlugins/SyntaxChecker/SyntaxCheck.py Thu Apr 15 18:11:24 2021 +0200 @@ -12,13 +12,11 @@ import re import traceback import multiprocessing - +import contextlib -try: +with contextlib.suppress(ImportError): from pyflakes.checker import Checker from pyflakes.messages import ImportStarUsed, ImportStarUsage -except ImportError: - pass VcsConflictMarkerRegExpList = ( re.compile( @@ -283,13 +281,11 @@ error = str(detail) return [{'error': (fn, line, 0, "", error)}] except Exception as detail: - try: + with contextlib.suppress(Exception): fn = detail.filename line = detail.lineno error = detail.msg return [{'error': (fn, line, 0, "", error)}] - except Exception: # secok - pass # pyflakes if not checkFlakes: @@ -309,11 +305,9 @@ _fn, lineno, col, message, msg_args = warning.getMessageData() lineFlags = extractLineFlags(lines[lineno - 1].strip()) - try: + with contextlib.suppress(IndexError): lineFlags += extractLineFlags(lines[lineno].strip(), flagsLine=True) - except IndexError: - pass if ( "__IGNORE_WARNING__" not in lineFlags and "noqa" not in lineFlags
--- a/eric6/Plugins/VcsPlugins/vcsGit/GitDiffDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsGit/GitDiffDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,8 @@ process. """ +import contextlib + from PyQt5.QtCore import pyqtSlot, QFileInfo, Qt from PyQt5.QtGui import QTextCursor from PyQt5.QtWidgets import QWidget, QDialogButtonBox @@ -144,12 +146,9 @@ self.filesCombo.clear() - try: + with contextlib.suppress(AttributeError): self.highlighter.regenerateRules() self.highlighter2.regenerateRules() - except AttributeError: - # backward compatibility - pass if diffMode in ["work2repo", "work2stage", "stage2repo", "work2stage2repo"]:
--- a/eric6/Plugins/VcsPlugins/vcsGit/GitLogBrowserDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsGit/GitLogBrowserDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -10,6 +10,7 @@ import os import collections import re +import contextlib from PyQt5.QtCore import ( pyqtSlot, Qt, QDate, QProcess, QTimer, QSize, QPoint, QFileInfo @@ -2113,11 +2114,8 @@ self.diffEdit.clear() self.diffLabel.setText(self.tr("Differences")) self.diffSelectLabel.clear() - try: + with contextlib.suppress(AttributeError): self.diffHighlighter.regenerateRules() - except AttributeError: - # backward compatibility - pass selectedItems = self.logTree.selectedItems() if len(selectedItems) == 1: @@ -2263,12 +2261,9 @@ if ":" in link: scheme, parent = link.split(":", 1) if scheme == "diff": - try: + with contextlib.suppress(ValueError): parent = int(parent) self.__generateDiffs(parent) - except ValueError: - # ignore silently - pass @pyqtSlot(str) def on_saveLabel_linkActivated(self, link):
--- a/eric6/Plugins/VcsPlugins/vcsGit/GitStatusDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsGit/GitStatusDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -10,6 +10,7 @@ import os import tempfile +import contextlib from PyQt5.QtCore import pyqtSlot, Qt, QProcess, QTimer, QSize from PyQt5.QtGui import QTextCursor @@ -1070,12 +1071,9 @@ """ self.lDiffEdit.clear() self.rDiffEdit.clear() - try: + with contextlib.suppress(AttributeError): self.lDiffHighlighter.regenerateRules() self.rDiffHighlighter.regenerateRules() - except AttributeError: - # backward compatibility - pass selectedItems = self.statusList.selectedItems() if len(selectedItems) == 1:
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/HgLogBrowserDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsMercurial/HgLogBrowserDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -854,14 +854,11 @@ if output: for line in output.splitlines(): if line.strip(): - try: + with contextlib.suppress(ValueError): name, rev = line.strip().rsplit(None, 1) if name == tag: res = tuple(rev.split(":", 1)) break - except ValueError: - # ignore silently - pass return res @@ -2626,12 +2623,9 @@ if ":" in link: scheme, parent = link.split(":", 1) if scheme == "diff": - try: + with contextlib.suppress(ValueError): parent = int(parent) self.__generateDiffs(parent) - except ValueError: - # ignore silently - pass @pyqtSlot(str) def on_saveLabel_linkActivated(self, link):
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/HgUserConfigDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsMercurial/HgUserConfigDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -9,6 +9,7 @@ import os from configparser import ConfigParser +import contextlib from PyQt5.QtCore import pyqtSlot, Qt, QEvent from PyQt5.QtWidgets import QDialog, QTreeWidgetItem @@ -310,7 +311,7 @@ self.__config = ConfigParser(delimiters=("=",)) if self.__config.read(cfgFile): # step 1: extract user name and email - try: + with contextlib.suppress(KeyError): username = self.__config["ui"]["username"].strip() if "<" in username and username.endswith(">"): name, email = username[:-1].rsplit("<", 1) @@ -319,8 +320,6 @@ email = "" self.userNameEdit.setText(name.strip()), self.emailEdit.setText(email.strip()), - except KeyError: - pass # step 2: extract extensions information if "extensions" in self.__config:
--- a/eric6/Plugins/VcsPlugins/vcsMercurial/hg.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsMercurial/hg.py Thu Apr 15 18:11:24 2021 +0200 @@ -1902,7 +1902,7 @@ lfMinSize, lfPattern = dlg.getLargefilesData() else: createContents = False - try: + with contextlib.suppress(OSError): with open(cfgFile, "w") as cfg: if createContents: # write the data entered @@ -1925,8 +1925,6 @@ "\n ".join(lfPattern))) self.__monitorRepoIniFile(repoName) self.__iniFileChanged(cfgFile) - except OSError: - pass self.repoEditor = MiniEditor(cfgFile, "Properties") self.repoEditor.show()
--- a/eric6/Plugins/VcsPlugins/vcsPySvn/subversion.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Plugins/VcsPlugins/vcsPySvn/subversion.py Thu Apr 15 18:11:24 2021 +0200 @@ -12,6 +12,7 @@ import shutil import time from urllib.parse import quote +import contextlib from PyQt5.QtCore import pyqtSignal, Qt, QDateTime, QCoreApplication from PyQt5.QtWidgets import QLineEdit, QDialog, QInputDialog, QApplication @@ -1479,7 +1480,7 @@ mixin._clientSslServerTrustPromptCallback ) - try: + with contextlib.suppress(pysvn.ClientError): with E5MutexLocker(self.vcsExecutionMutex): allFiles = client.status(dname, recurse=True, get_all=True, ignore=True, update=False) @@ -1512,9 +1513,6 @@ break else: self.statusCache[name] = self.canBeAdded - except pysvn.ClientError: - # ignore pysvn errors - pass return names @@ -1559,7 +1557,7 @@ mixin._clientSslServerTrustPromptCallback ) - try: + with contextlib.suppress(pysvn.ClientError): with E5MutexLocker(self.vcsExecutionMutex): allFiles = client.status(dname, recurse=True, get_all=True, ignore=True, update=False) @@ -1571,9 +1569,6 @@ self.statusCache[name] = self.canBeCommitted else: self.statusCache[name] = self.canBeAdded - except pysvn.ClientError: - # ignore pysvn errors - pass return names @@ -2455,7 +2450,7 @@ client = self.getClient() if hasattr(client, 'get_changelist'): ppath = e5App().getObject("Project").getProjectPath() - try: + with contextlib.suppress(pysvn.ClientError): with E5MutexLocker(self.vcsExecutionMutex): entries = client.get_changelist( ppath, depth=pysvn.depth.infinity) @@ -2463,8 +2458,6 @@ changelist = entry[1] if changelist not in changelists: changelists.append(changelist) - except pysvn.ClientError: - pass return changelists
--- a/eric6/Preferences/ConfigurationDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Preferences/ConfigurationDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -9,6 +9,7 @@ import os import types +import contextlib from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QMetaObject, QRect from PyQt5.QtGui import QPixmap @@ -642,10 +643,8 @@ self.lexers = {} for language in QScintilla.Lexers.getSupportedLanguages(): if language not in self.lexers: - try: + with contextlib.suppress(PreferencesLexerLanguageError): self.lexers[language] = PreferencesLexer(language, self) - except PreferencesLexerLanguageError: - pass def __importConfigurationPage(self, name): """ @@ -696,10 +695,8 @@ if page is not None: self.configStack.addWidget(page) pageData[-1] = page - try: + with contextlib.suppress(AttributeError): page.setMode(self.displayMode) - except AttributeError: - pass return page def showConfigurationPageByName(self, pageName, setCurrent=True):
--- a/eric6/Preferences/ConfigurationPages/WebBrowserSpellCheckingPage.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Preferences/ConfigurationPages/WebBrowserSpellCheckingPage.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import ( pyqtSlot, Qt, QCoreApplication, QDir, QLibraryInfo, QLocale @@ -65,11 +66,8 @@ # try to create these directories, if they don't exist for directory in self.__dictionaryDirectories: if not os.path.exists(directory): - try: + with contextlib.suppress(os.error): os.makedirs(directory) - except os.error: - # ignore it - pass self.__writeableDirectories = [] for directory in self.__dictionaryDirectories:
--- a/eric6/Preferences/Shortcuts.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Preferences/Shortcuts.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing functions dealing with keyboard shortcuts. """ +import contextlib + from PyQt5.QtCore import QFile, QIODevice, QCoreApplication from PyQt5.QtGui import QKeySequence @@ -95,15 +97,12 @@ __readShortcut(act, helpViewerCategory, prefClass) if pluginName is not None: - try: + with contextlib.suppress(KeyError): ref = e5App().getPluginObject(pluginName) if hasattr(ref, "getActions"): actions = ref.getActions() for act in actions: __readShortcut(act, pluginName, prefClass) - except KeyError: - # silently ignore non available plugins - pass def __saveShortcut(act, category, prefClass): @@ -292,13 +291,11 @@ """ for act in actions: if act.objectName(): - try: + with contextlib.suppress(KeyError): accel, altAccel = shortcutsDict[act.objectName()] act.setShortcut(QKeySequence(accel)) act.setAlternateShortcut(QKeySequence(altAccel), removeEmpty=True) - except KeyError: - pass def setActions(shortcuts, helpViewer=None):
--- a/eric6/Preferences/__init__.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Preferences/__init__.py Thu Apr 15 18:11:24 2021 +0200 @@ -22,6 +22,7 @@ import shutil import json import sys +import contextlib from PyQt5.QtCore import ( QDir, QPoint, QLocale, QSettings, QFileInfo, QCoreApplication, QByteArray, @@ -1148,15 +1149,13 @@ webEngineSettings.testAttribute( QWebEngineSettings.WebAttribute.DnsPrefetchEnabled), }) - try: + with contextlib.suppress(AttributeError): # Qt 5.13 cls.webBrowserDefaults.update({ "PdfViewerEnabled": webEngineSettings.testAttribute( QWebEngineSettings.WebAttribute.PdfViewerEnabled), }) - except AttributeError: - pass cls.webEngineSettingsIntitialized = True @@ -1614,11 +1613,9 @@ dn.mkdir(".eric6") QCoreApplication.setOrganizationName(Globals.settingsNameOrganization) QCoreApplication.setApplicationName(Globals.settingsNameGlobal) - try: + with contextlib.suppress(AttributeError): Prefs.settings.setAtomicSyncRequired(False) - except AttributeError: - # backward compatibility fot Qt < 5.10 - pass + # backward compatibility for Qt < 5.10 Prefs.settings.value("UI/SingleApplicationMode")
--- a/eric6/Project/CreateDialogCodeDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Project/CreateDialogCodeDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -10,6 +10,7 @@ import sys import os import json +import contextlib from PyQt5.QtCore import ( pyqtSlot, Qt, QMetaObject, QRegularExpression, QSortFilterProxyModel, @@ -96,14 +97,12 @@ self.__initError = True return - try: + with contextlib.suppress(ImportError): splitExt = os.path.splitext(self.srcFile) exts = [splitExt[1]] if len(splitExt) == 2 else None from Utilities import ModuleParser self.__module = ModuleParser.readModule( self.srcFile, extensions=exts, caching=False) - except ImportError: - pass if self.__module is not None: self.filenameEdit.setText(self.srcFile)
--- a/eric6/Project/FiletypeAssociationDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Project/FiletypeAssociationDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a dialog to enter filetype associations for the project. """ +import contextlib + from PyQt5.QtCore import Qt, pyqtSlot from PyQt5.QtWidgets import QHeaderView, QDialog, QTreeWidgetItem @@ -46,11 +48,9 @@ self.project = project for pattern, filetype in list(self.project.pdata["FILETYPES"].items()): - try: + with contextlib.suppress(ValueError): index = self.filetypes.index(filetype) self.__createItem(pattern, self.filetypeStrings[index]) - except ValueError: - pass # silently discard entries of unknown type self.__resort() self.__reformat()
--- a/eric6/Project/Project.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Project/Project.py Thu Apr 15 18:11:24 2021 +0200 @@ -1488,15 +1488,13 @@ self.pdata["TRANSLATIONS"].remove(langFile) self.__model.removeItem(langFile) if qmFile: - try: + with contextlib.suppress(ValueError): if self.pdata["TRANSLATIONSBINPATH"]: qmFile = self.getRelativePath( os.path.join(self.pdata["TRANSLATIONSBINPATH"], os.path.basename(qmFile))) self.pdata["TRANSLATIONS"].remove(qmFile) self.__model.removeItem(qmFile) - except ValueError: - pass self.setDirty(True) def deleteLanguageFile(self, langFile): @@ -4885,17 +4883,13 @@ if vcs and forProject: # set the vcs options if vcs.vcsSupportCommandOptions(): - try: + with contextlib.suppress(LookupError): vcsopt = copy.deepcopy(self.pdata["VCSOPTIONS"]) vcs.vcsSetOptions(vcsopt) - except LookupError: - pass # set vcs specific data - try: + with contextlib.suppress(LookupError): vcsother = copy.deepcopy(self.pdata["VCSOTHERDATA"]) vcs.vcsSetOtherData(vcsother) - except LookupError: - pass if forProject: if vcs is None:
--- a/eric6/Project/ProjectBaseBrowser.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Project/ProjectBaseBrowser.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import ( QModelIndex, pyqtSignal, Qt, QCoreApplication, QItemSelectionModel, @@ -591,12 +592,10 @@ childIndex = self.model().index(0, 0) while childIndex.isValid(): if self.isExpanded(childIndex): - try: + with contextlib.suppress(AttributeError): expandedNames.append( self.model().item(childIndex).name()) - except AttributeError: # only items defining the name() method are returned - pass childIndex = self.indexBelow(childIndex) return expandedNames @@ -611,13 +610,11 @@ for name in names: childIndex = model.index(0, 0) while childIndex.isValid(): - try: + with contextlib.suppress(AttributeError): if model.item(childIndex).name() == name: self.setExpanded(childIndex, True) break - except AttributeError: # ignore items not supporting this method - pass childIndex = self.indexBelow(childIndex) def _prepareRepopulateItem(self, name):
--- a/eric6/Project/ProjectBrowserModel.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Project/ProjectBrowserModel.py Thu Apr 15 18:11:24 2021 +0200 @@ -9,6 +9,7 @@ import os import re +import contextlib from PyQt5.QtCore import QDir, QModelIndex, pyqtSignal, QFileSystemWatcher, Qt from PyQt5.QtGui import QColor @@ -645,15 +646,13 @@ else: break for child in itm.children(): - try: + with contextlib.suppress(AttributeError): start, end = child.boundaries() if end == -1: end = 1000000 # assume end of file if start <= lineno <= end: itm = child break - except AttributeError: - pass else: itm = None if itm:
--- a/eric6/Project/ProjectBrowserSortFilterProxyModel.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Project/ProjectBrowserSortFilterProxyModel.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing the browser sort filter proxy model. """ +import contextlib + from UI.BrowserSortFilterProxyModel import BrowserSortFilterProxyModel from .ProjectBrowserModel import ProjectBrowserSourceType @@ -45,7 +47,7 @@ if not sindex.isValid(): return False sitem = self.sourceModel().item(sindex) - try: + with contextlib.suppress(AttributeError): if self.__filterType not in sitem.getProjectTypes(): return False if ( @@ -54,8 +56,6 @@ sitem.data(0).startswith("Ui_") ): return False - except AttributeError: - pass if self.hideNonPublic: return sitem.isPublic()
--- a/eric6/Project/ProjectFormsBrowser.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Project/ProjectFormsBrowser.py Thu Apr 15 18:11:24 2021 +0200 @@ -391,7 +391,7 @@ self.__pyuicDirMultiConfigAct.setEnabled(enable) self.__pyuicBackConfigAct.setEnabled(enable) - try: + with contextlib.suppress(Exception): categories = self.getSelectedItemsCountCategorized( [ProjectBrowserFileItem, ProjectBrowserSimpleDirectoryItem]) cnt = categories["sum"] @@ -421,8 +421,6 @@ self.backMenu.popup(self.mapToGlobal(coord)) else: self.backMenu.popup(self.mapToGlobal(coord)) - except Exception: # secok - pass def __showContextMenu(self): """
--- a/eric6/Project/ProjectInterfacesBrowser.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Project/ProjectInterfacesBrowser.py Thu Apr 15 18:11:24 2021 +0200 @@ -10,6 +10,7 @@ import os import glob +import contextlib from PyQt5.QtCore import QThread, pyqtSignal, QProcess from PyQt5.QtWidgets import QDialog, QApplication, QMenu @@ -294,7 +295,7 @@ if not self.project.isOpen(): return - try: + with contextlib.suppress(Exception): categories = self.getSelectedItemsCountCategorized( [ProjectBrowserFileItem, BrowserClassItem, BrowserMethodItem, ProjectBrowserSimpleDirectoryItem]) @@ -338,8 +339,6 @@ self.backMenu.popup(self.mapToGlobal(coord)) else: self.backMenu.popup(self.mapToGlobal(coord)) - except Exception: # secok - pass def __showContextMenu(self): """
--- a/eric6/Project/ProjectOthersBrowser.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Project/ProjectOthersBrowser.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,8 @@ don't fit the other categories. """ +import contextlib + from PyQt5.QtCore import QModelIndex, pyqtSignal, QUrl from PyQt5.QtGui import QDesktopServices from PyQt5.QtWidgets import QDialog, QMenu @@ -144,7 +146,7 @@ if not self.project.isOpen(): return - try: + with contextlib.suppress(Exception): cnt = self.getSelectedItemsCount() if cnt <= 1: index = self.indexAt(coord) @@ -170,8 +172,6 @@ self.backMenu.popup(self.mapToGlobal(coord)) else: self.backMenu.popup(self.mapToGlobal(coord)) - except Exception: # secok - pass def __showContextMenu(self): """
--- a/eric6/Project/ProjectProtocolsBrowser.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Project/ProjectProtocolsBrowser.py Thu Apr 15 18:11:24 2021 +0200 @@ -11,6 +11,7 @@ import os import glob import sys +import contextlib from PyQt5.QtCore import QThread, pyqtSignal, QProcess from PyQt5.QtWidgets import QDialog, QApplication, QMenu @@ -286,7 +287,7 @@ if not self.project.isOpen(): return - try: + with contextlib.suppress(Exception): categories = self.getSelectedItemsCountCategorized( [ProjectBrowserFileItem, BrowserClassItem, BrowserMethodItem, ProjectBrowserSimpleDirectoryItem]) @@ -330,8 +331,6 @@ self.backMenu.popup(self.mapToGlobal(coord)) else: self.backMenu.popup(self.mapToGlobal(coord)) - except Exception: # secok - pass def __showContextMenu(self): """
--- a/eric6/Project/ProjectResourcesBrowser.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Project/ProjectResourcesBrowser.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import QThread, QFileInfo, pyqtSignal, QProcess from PyQt5.QtWidgets import QDialog, QApplication, QMenu @@ -327,7 +328,7 @@ if not self.project.isOpen(): return - try: + with contextlib.suppress(Exception): categories = self.getSelectedItemsCountCategorized( [ProjectBrowserFileItem, ProjectBrowserSimpleDirectoryItem]) cnt = categories["sum"] @@ -357,8 +358,6 @@ self.backMenu.popup(self.mapToGlobal(coord)) else: self.backMenu.popup(self.mapToGlobal(coord)) - except Exception: # secok - pass def __showContextMenu(self): """
--- a/eric6/Project/ProjectSourcesBrowser.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Project/ProjectSourcesBrowser.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import pyqtSignal from PyQt5.QtWidgets import QDialog, QInputDialog, QMenu @@ -580,7 +581,7 @@ if not self.project.isOpen(): return - try: + with contextlib.suppress(Exception): categories = self.getSelectedItemsCountCategorized( [ProjectBrowserFileItem, BrowserClassItem, BrowserMethodItem, ProjectBrowserSimpleDirectoryItem, @@ -669,8 +670,6 @@ self.backMenu.popup(self.mapToGlobal(coord)) else: self.backMenu.popup(self.mapToGlobal(coord)) - except Exception: # secok - pass def __showContextMenu(self): """
--- a/eric6/Project/ProjectTranslationsBrowser.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Project/ProjectTranslationsBrowser.py Thu Apr 15 18:11:24 2021 +0200 @@ -12,6 +12,7 @@ import shutil import fnmatch import functools +import contextlib from PyQt5.QtCore import pyqtSignal, QProcess from PyQt5.QtWidgets import QDialog, QMenu @@ -461,7 +462,7 @@ if not self.project.isOpen(): return - try: + with contextlib.suppress(Exception): categories = self.getSelectedItemsCountCategorized( [ProjectBrowserFileItem, ProjectBrowserSimpleDirectoryItem]) cnt = categories["sum"] @@ -489,8 +490,6 @@ self.backMenu.popup(self.mapToGlobal(coord)) else: self.backMenu.popup(self.mapToGlobal(coord)) - except Exception: # secok - pass def __showContextMenu(self): """ @@ -963,11 +962,9 @@ if proc == self.__pylupdateProcesses[index][0]: tmpProjectFile = self.__pylupdateProcesses[index][1] if tmpProjectFile: - try: + with contextlib.suppress(OSError): self.__tmpProjects.remove(tmpProjectFile) os.remove(tmpProjectFile) - except OSError: - pass del self.__pylupdateProcesses[index] break @@ -1130,11 +1127,9 @@ 'Ensure that it is in the search path.' ).format(self.pylupdate)) # cleanup - try: + with contextlib.suppress(OSError): self.__tmpProjects.remove(tempProjectFile) os.remove(tempProjectFile) - except OSError: - pass def __generateAll(self): """
--- a/eric6/QScintilla/Editor.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Editor.py Thu Apr 15 18:11:24 2021 +0200 @@ -1614,11 +1614,9 @@ """ Private method to check the selected encoding of the encodings submenu. """ - try: + with contextlib.suppress(AttributeError, KeyError): (self.supportedEncodings[self.__normalizedEncoding()] .setChecked(True)) - except (AttributeError, KeyError): - pass def __encodingChanged(self, encoding, propagate=True): """ @@ -1671,10 +1669,8 @@ """ Private method to check the selected eol type of the eol submenu. """ - try: + with contextlib.suppress(AttributeError, TypeError): self.supportedEols[self.getLineSeparator()].setChecked(True) - except (AttributeError, TypeError): - pass def __eolChanged(self): """ @@ -1711,10 +1707,8 @@ Private slot to check the selected spell check language action. """ language = self.getSpellingLanguage() - try: + with contextlib.suppress(AttributeError, KeyError): self.supportedSpellLanguages[language].setChecked(True) - except (AttributeError, KeyError): - pass def __spellLanguageChanged(self, language, propagate=True): """ @@ -4527,10 +4521,8 @@ if Preferences.getEditor("FoldingMargin"): self.setMarginWidth(self.__foldMargin, 16) folding = Preferences.getEditor("FoldingStyle") - try: + with contextlib.suppress(AttributeError): folding = QsciScintilla.FoldStyle(folding) - except AttributeError: - pass self.setFolding(folding, self.__foldMargin) self.setFoldMarginColors( Preferences.getEditorColour("FoldmarginBackground"), @@ -4580,16 +4572,13 @@ if Preferences.getEditor("ShowWhitespace"): self.setWhitespaceVisibility( QsciScintilla.WhitespaceVisibility.WsVisible) - try: + with contextlib.suppress(AttributeError): self.setWhitespaceForegroundColor( Preferences.getEditorColour("WhitespaceForeground")) self.setWhitespaceBackgroundColor( Preferences.getEditorColour("WhitespaceBackground")) self.setWhitespaceSize( Preferences.getEditor("WhitespaceSize")) - except AttributeError: - # QScintilla before 2.5 doesn't support this - pass else: self.setWhitespaceVisibility( QsciScintilla.WhitespaceVisibility.WsInvisible) @@ -4675,15 +4664,13 @@ self.setCursorFlashTime(QApplication.cursorFlashTime()) - try: + with contextlib.suppress(AttributeError): if Preferences.getEditor("AnnotationsEnabled"): self.setAnnotationDisplay( QsciScintilla.AnnotationDisplay.AnnotationBoxed) else: self.setAnnotationDisplay( QsciScintilla.AnnotationDisplay.AnnotationHidden) - except AttributeError: - pass self.__setAnnotationStyles() if Preferences.getEditor("OverrideEditAreaColours"): @@ -4768,11 +4755,9 @@ Preferences.getEditorColour("CallTipsHighlight")) self.setCallTipsVisible(Preferences.getEditor("CallTipsVisible")) calltipsStyle = Preferences.getEditor("CallTipsStyle") - try: + with contextlib.suppress(AttributeError): self.setCallTipsPosition( Preferences.getEditor("CallTipsPosition")) - except AttributeError: - pass if Preferences.getEditor("CallTipsEnabled"): if calltipsStyle == QsciScintilla.CallTipsStyle.CallTipsNoContext: @@ -7000,11 +6985,9 @@ if self.spell: self.spell.stopIncrementalCheck() - try: + with contextlib.suppress(TypeError): self.project.projectPropertiesChanged.disconnect( self.__projectPropertiesChanged) - except TypeError: - pass if self.fileName: self.taskViewer.clearFileTasks(self.fileName, True) @@ -7071,10 +7054,8 @@ self.vm.copyActGrp.setEnabled(True) self.vm.viewActGrp.setEnabled(True) self.vm.searchActGrp.setEnabled(True) - try: + with contextlib.suppress(AttributeError): self.setCaretWidth(self.caretWidth) - except AttributeError: - pass self.__updateReadOnly(False) if ( self.vm.editorsCheckFocusInEnabled() and @@ -7258,12 +7239,8 @@ @return flag indiating that the event was handled @rtype bool """ - try: + with contextlib.suppress(AttributeError): self.__markerMap.calculateGeometry() - except AttributeError: - # ignore this - there seems to be a runtime issue when the editor - # is created - pass return super().viewportEvent(evt) def __updateReadOnly(self, bForce=True): @@ -7780,11 +7757,9 @@ """ Public slot to handle the closing of a project. """ - try: + with contextlib.suppress(TypeError): self.project.projectPropertiesChanged.disconnect( self.__projectPropertiesChanged) - except TypeError: - pass ####################################################################### ## Spell checking related methods @@ -7852,17 +7827,13 @@ Public method to set the automatic spell checking. """ if Preferences.getEditor("AutoSpellCheckingEnabled"): - try: + with contextlib.suppress(TypeError): self.SCN_CHARADDED.connect( self.__spellCharAdded, Qt.ConnectionType.UniqueConnection) - except TypeError: - pass self.spell.checkDocumentIncrementally() else: - try: + with contextlib.suppress(TypeError): self.SCN_CHARADDED.disconnect(self.__spellCharAdded) - except TypeError: - pass self.clearAllIndicators(self.spellingIndicator) def isSpellCheckRegion(self, pos):
--- a/eric6/QScintilla/EditorAssembly.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/EditorAssembly.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,8 @@ combos and the editor widget. """ +import contextlib + from PyQt5.QtCore import QTimer from PyQt5.QtWidgets import QWidget, QGridLayout, QComboBox @@ -148,7 +150,7 @@ line, _ = self.__editor.getCursorPosition() self.__editorCursorLineChanged(line) else: - try: + with contextlib.suppress(TypeError): self.__globalsCombo.activated[int].disconnect( self.__globalsActivated) self.__membersCombo.activated[int].disconnect( @@ -156,9 +158,6 @@ self.__editor.cursorLineChanged.disconnect( self.__editorCursorLineChanged) self.__parseTimer.timeout.disconnect(self.__parseEditor) - except TypeError: - # signals were not connected - pass self.__globalsCombo.clear() self.__membersCombo.clear() @@ -449,14 +448,11 @@ else: self.__sourceOutline.hide() - try: + with contextlib.suppress(TypeError): self.__parseTimer.timeout.disconnect( self.__sourceOutline.repopulate) self.__editor.languageChanged.disconnect(self.__editorChanged) self.__editor.editorRenamed.disconnect(self.__editorChanged) - except TypeError: - # signals were not connected - pass def __editorChanged(self): """
--- a/eric6/QScintilla/EditorButtonsWidget.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/EditorButtonsWidget.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,8 @@ editor actions. """ +import contextlib + from PyQt5.QtCore import pyqtSlot, Qt from PyQt5.QtWidgets import ( QWidget, QVBoxLayout, QToolButton, QFrame, QMenu, QSizePolicy, QScrollArea @@ -305,11 +307,9 @@ elif formatName == "strikethrough": self.__provider.strikethrough(self.__editor) elif formatName.startswith("header"): - try: + with contextlib.suppress(ValueError): level = int(formatName[-1]) self.__provider.header(self.__editor, level) - except ValueError: - pass elif formatName == "code": self.__provider.code(self.__editor) elif formatName == "codeBlock":
--- a/eric6/QScintilla/EditorOutline.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/EditorOutline.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing an outline widget for source code navigation of the editor. """ +import contextlib + from PyQt5.QtCore import pyqtSlot, Qt, QCoreApplication, QModelIndex, QPoint from PyQt5.QtWidgets import QTreeView, QAbstractItemView, QMenu, QApplication @@ -186,12 +188,9 @@ if index.isValid(): itm = self.model().item(index) if itm: - try: + with contextlib.suppress(AttributeError): lineno = itm.lineno() self.__model.editor().gotoLine(lineno) - except AttributeError: - # don't care - pass def mouseDoubleClickEvent(self, mouseEvent): """
--- a/eric6/QScintilla/EditorOutlineModel.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/EditorOutlineModel.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import QCoreApplication, QModelIndex @@ -106,13 +107,11 @@ # special treatment done later continue cl = dictionary[key] - try: + with contextlib.suppress(AttributeError): if cl.module == self.__module: node = BrowserClassItem( parentItem, cl, self.__filename) self._addItem(node, parentItem) - except AttributeError: - pass if ( "@@Coding@@" in keys and Preferences.getEditor("SourceOutlineShowCoding")
--- a/eric6/QScintilla/Exporters/ExporterHTML.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Exporters/ExporterHTML.py Thu Apr 15 18:11:24 2021 +0200 @@ -13,6 +13,7 @@ import os import sys import io +import contextlib from PyQt5.QtGui import QFontInfo from PyQt5.QtWidgets import QInputDialog @@ -578,7 +579,7 @@ pyMdown = False if Preferences.getEditor("PreviewMarkdownUsePyMdownExtensions"): - try: + with contextlib.suppress(ImportError): import pymdownx # __IGNORE_EXCEPTION__ __IGNORE_WARNING__ # PyPI package is 'pymdown-extensions' @@ -589,8 +590,6 @@ 'pymdownx.tasklist', 'pymdownx.smartsymbols', ]) pyMdown = True - except ImportError: - pass if not pyMdown: extensions.extend(['extra', 'toc'])
--- a/eric6/QScintilla/Lexers/LexerCPP.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Lexers/LexerCPP.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a CPP lexer with some additional methods. """ +import contextlib + from PyQt5.Qsci import QsciLexerCPP, QsciScintilla from .SubstyledLexer import SubstyledLexer @@ -112,41 +114,27 @@ indentStyle |= QsciScintilla.AiClosing self.setAutoIndentStyle(indentStyle) self.setFoldCompact(Preferences.getEditor("AllFoldCompact")) - try: + with contextlib.suppress(AttributeError): self.setDollarsAllowed(Preferences.getEditor("CppDollarsAllowed")) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): self.setStylePreprocessor( Preferences.getEditor("CppStylePreprocessor")) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): self.setHighlightTripleQuotedStrings( Preferences.getEditor("CppHighlightTripleQuotedStrings")) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): self.setHighlightHashQuotedStrings( Preferences.getEditor("CppHighlightHashQuotedStrings")) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): self.setHighlightBackQuotedStrings( Preferences.getEditor("CppHighlightBackQuotedStrings")) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): self.setHighlightEscapeSequences( Preferences.getEditor("CppHighlightEscapeSequences")) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): self.setVerbatimStringEscapeSequencesAllowed( Preferences.getEditor( "CppVerbatimStringEscapeSequencesAllowed")) - except AttributeError: - pass def autoCompletionWordSeparators(self): """
--- a/eric6/QScintilla/Lexers/LexerCSS.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Lexers/LexerCSS.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a CSS lexer with some additional methods. """ +import contextlib + from PyQt5.Qsci import QsciLexerCSS from .Lexer import Lexer @@ -49,15 +51,13 @@ """ self.setFoldComments(Preferences.getEditor("CssFoldComment")) self.setFoldCompact(Preferences.getEditor("AllFoldCompact")) - try: + with contextlib.suppress(AttributeError): self.setHSSLanguage( Preferences.getEditor("CssHssSupport")) self.setLessLanguage( Preferences.getEditor("CssLessSupport")) self.setSCSSLanguage( Preferences.getEditor("CssSassySupport")) - except AttributeError: - pass def isCommentStyle(self, style): """
--- a/eric6/QScintilla/Lexers/LexerHTML.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Lexers/LexerHTML.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a HTML lexer with some additional methods. """ +import contextlib + from PyQt5.Qsci import QsciLexerHTML from .Lexer import Lexer @@ -48,19 +50,15 @@ self.setCaseSensitiveTags( Preferences.getEditor("HtmlCaseSensitiveTags")) self.setFoldCompact(Preferences.getEditor("AllFoldCompact")) - try: + with contextlib.suppress(AttributeError): self.setFoldScriptComments( Preferences.getEditor("HtmlFoldScriptComments")) self.setFoldScriptHeredocs( Preferences.getEditor("HtmlFoldScriptHeredocs")) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): self.setDjangoTemplates( Preferences.getEditor("HtmlDjangoTemplates")) self.setMakoTemplates(Preferences.getEditor("HtmlMakoTemplates")) - except AttributeError: - pass def isCommentStyle(self, style): """
--- a/eric6/QScintilla/Lexers/LexerPascal.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Lexers/LexerPascal.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a Pascal lexer with some additional methods. """ +import contextlib + from PyQt5.Qsci import QsciLexerPascal from .Lexer import Lexer @@ -44,11 +46,9 @@ self.setFoldPreprocessor( Preferences.getEditor("PascalFoldPreprocessor")) self.setFoldCompact(Preferences.getEditor("AllFoldCompact")) - try: + with contextlib.suppress(AttributeError): self.setSmartHighlighting( Preferences.getEditor("PascalSmartHighlighting")) - except AttributeError: - pass def autoCompletionWordSeparators(self): """
--- a/eric6/QScintilla/Lexers/LexerPerl.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Lexers/LexerPerl.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a Perl lexer with some additional methods. """ +import contextlib + from PyQt5.Qsci import QsciLexerPerl from .Lexer import Lexer @@ -38,15 +40,11 @@ """ self.setFoldComments(Preferences.getEditor("PerlFoldComment")) self.setFoldCompact(Preferences.getEditor("AllFoldCompact")) - try: + with contextlib.suppress(AttributeError): self.setFoldPackages(Preferences.getEditor("PerlFoldPackages")) self.setFoldPODBlocks(Preferences.getEditor("PerlFoldPODBlocks")) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): self.setFoldAtElse(Preferences.getEditor("PerlFoldAtElse")) - except AttributeError: - pass def autoCompletionWordSeparators(self): """
--- a/eric6/QScintilla/Lexers/LexerProperties.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Lexers/LexerProperties.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a Properties lexer with some additional methods. """ +import contextlib + from PyQt5.Qsci import QsciLexerProperties from .Lexer import Lexer @@ -35,11 +37,9 @@ Public slot to initialize the properties. """ self.setFoldCompact(Preferences.getEditor("AllFoldCompact")) - try: + with contextlib.suppress(AttributeError): self.setInitialSpaces( Preferences.getEditor("PropertiesInitialSpaces")) - except AttributeError: - pass def isCommentStyle(self, style): """
--- a/eric6/QScintilla/Lexers/LexerPython.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Lexers/LexerPython.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import re +import contextlib from PyQt5.Qsci import QsciLexerPython, QsciScintilla @@ -130,26 +131,20 @@ self.setFoldQuotes(Preferences.getEditor("PythonFoldString")) if not Preferences.getEditor("PythonAutoIndent"): self.setAutoIndentStyle(QsciScintilla.AiMaintain) - try: + with contextlib.suppress(AttributeError): self.setV2UnicodeAllowed( Preferences.getEditor("PythonAllowV2Unicode")) self.setV3BinaryOctalAllowed( Preferences.getEditor("PythonAllowV3Binary")) self.setV3BytesAllowed(Preferences.getEditor("PythonAllowV3Bytes")) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): self.setFoldQuotes(Preferences.getEditor("PythonFoldQuotes")) self.setStringsOverNewlineAllowed( Preferences.getEditor("PythonStringsOverNewLineAllowed")) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): self.setHighlightSubidentifiers( Preferences.getEditor("PythonHighlightSubidentifier")) - except AttributeError: - pass - + def getIndentationDifference(self, line, editor): """ Public method to determine the difference for the new indentation.
--- a/eric6/QScintilla/Lexers/LexerQSS.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Lexers/LexerQSS.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a QSS lexer with some additional methods. """ +import contextlib + from PyQt5.Qsci import QsciLexerCSS from .Lexer import Lexer @@ -49,15 +51,13 @@ """ self.setFoldComments(Preferences.getEditor("CssFoldComment")) self.setFoldCompact(Preferences.getEditor("AllFoldCompact")) - try: + with contextlib.suppress(AttributeError): self.setHSSLanguage( Preferences.getEditor("CssHssSupport")) self.setLessLanguage( Preferences.getEditor("CssLessSupport")) self.setSCSSLanguage( Preferences.getEditor("CssSassySupport")) - except AttributeError: - pass def isCommentStyle(self, style): """
--- a/eric6/QScintilla/Lexers/LexerRuby.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Lexers/LexerRuby.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a Ruby lexer with some additional methods. """ +import contextlib + from PyQt5.Qsci import QsciLexerRuby from .Lexer import Lexer @@ -36,11 +38,9 @@ """ Public slot to initialize the properties. """ - try: + with contextlib.suppress(AttributeError): self.setFoldCompact(Preferences.getEditor("AllFoldCompact")) self.setFoldComments(Preferences.getEditor("RubyFoldComment")) - except AttributeError: - pass def autoCompletionWordSeparators(self): """
--- a/eric6/QScintilla/Lexers/LexerSQL.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Lexers/LexerSQL.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a SQL lexer with some additional methods. """ +import contextlib + from PyQt5.Qsci import QsciLexerSQL from .Lexer import Lexer @@ -46,15 +48,13 @@ self.setFoldComments(Preferences.getEditor("SqlFoldComment")) self.setBackslashEscapes(Preferences.getEditor("SqlBackslashEscapes")) self.setFoldCompact(Preferences.getEditor("AllFoldCompact")) - try: + with contextlib.suppress(AttributeError): self.setDottedWords(Preferences.getEditor("SqlDottedWords")) self.setFoldAtElse(Preferences.getEditor("SqlFoldAtElse")) self.setFoldOnlyBegin(Preferences.getEditor("SqlFoldOnlyBegin")) self.setHashComments(Preferences.getEditor("SqlHashComments")) self.setQuotedIdentifiers( Preferences.getEditor("SqlQuotedIdentifiers")) - except AttributeError: - pass def isCommentStyle(self, style): """
--- a/eric6/QScintilla/Lexers/LexerTCL.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Lexers/LexerTCL.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a TCL/Tk lexer with some additional methods. """ +import contextlib + from PyQt5.Qsci import QsciLexerTCL from .Lexer import Lexer @@ -45,14 +47,10 @@ """ Public slot to initialize the properties. """ - try: + with contextlib.suppress(AttributeError): self.setFoldCompact(Preferences.getEditor("AllFoldCompact")) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): self.setFoldComments(Preferences.getEditor("TclFoldComment")) - except AttributeError: - pass def isCommentStyle(self, style): """
--- a/eric6/QScintilla/Lexers/LexerTeX.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Lexers/LexerTeX.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a Tex lexer with some additional methods. """ +import contextlib + from PyQt5.Qsci import QsciLexerTeX from .Lexer import Lexer @@ -43,14 +45,12 @@ """ Public slot to initialize the properties. """ - try: + with contextlib.suppress(AttributeError): self.setFoldCompact(Preferences.getEditor("AllFoldCompact")) self.setFoldComments(Preferences.getEditor("TexFoldComment")) self.setProcessComments( Preferences.getEditor("TexProcessComments")) self.setProcessIf(Preferences.getEditor("TexProcessIf")) - except AttributeError: - pass def isCommentStyle(self, style): """
--- a/eric6/QScintilla/Lexers/LexerXML.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Lexers/LexerXML.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a XML lexer with some additional methods. """ +import contextlib + from PyQt5.Qsci import QsciLexerXML from .Lexer import Lexer @@ -48,14 +50,12 @@ self.setCaseSensitiveTags( Preferences.getEditor("HtmlCaseSensitiveTags")) self.setFoldCompact(Preferences.getEditor("AllFoldCompact")) - try: + with contextlib.suppress(AttributeError): self.setFoldScriptComments( Preferences.getEditor("HtmlFoldScriptComments")) self.setFoldScriptHeredocs( Preferences.getEditor("HtmlFoldScriptHeredocs")) self.setScriptsStyled(Preferences.getEditor("XMLStyleScripts")) - except AttributeError: - pass def isCommentStyle(self, style): """
--- a/eric6/QScintilla/MiniEditor.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/MiniEditor.py Thu Apr 15 18:11:24 2021 +0200 @@ -9,6 +9,7 @@ import os import re +import contextlib from PyQt5.QtCore import ( pyqtSignal, Qt, QSignalMapper, QPoint, QTimer, QFileInfo, QSize, @@ -151,10 +152,8 @@ @type QFocusEvent """ self.mw.editorActGrp.setEnabled(True) - try: + with contextlib.suppress(AttributeError): self.setCaretWidth(self.mw.caretWidth) - except AttributeError: - pass self.setCursorFlashTime(QApplication.cursorFlashTime()) @@ -2861,10 +2860,8 @@ self.__textEdit.setMarginWidth(2, 16) if Preferences.getEditor("FoldingMargin"): folding = Preferences.getEditor("FoldingStyle") - try: + with contextlib.suppress(AttributeError): folding = QsciScintilla.FoldStyle(folding) - except AttributeError: - pass self.__textEdit.setFolding(folding) self.__textEdit.setFoldMarginColors( Preferences.getEditorColour("FoldmarginBackground"),
--- a/eric6/QScintilla/QsciScintillaCompat.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/QsciScintillaCompat.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a compatability interface class to QsciScintilla. """ +import contextlib + from PyQt5.QtCore import pyqtSignal, Qt, QPoint from PyQt5.QtGui import QPalette, QColor, QFontMetrics from PyQt5.QtWidgets import QApplication, QListWidget @@ -759,11 +761,9 @@ @param alwaysVisible flag indicating that the caret line shall be visible even if the editor doesn't have the focus (boolean) """ - try: + with contextlib.suppress(AttributeError): self.SendScintilla( QsciScintilla.SCI_SETCARETLINEVISIBLEALWAYS, alwaysVisible) - except AttributeError: - pass def canPaste(self): """ @@ -910,12 +910,10 @@ self.__targetSearchFlags |= QsciScintilla.SCFIND_WORDSTART if posix: self.__targetSearchFlags |= QsciScintilla.SCFIND_POSIX - try: + with contextlib.suppress(AttributeError): if cxx11: self.__targetSearchFlags |= QsciScintilla.SCFIND_CXX11REGEX - except AttributeError: # defined for QScintilla >= 2.11.0 - pass if begline < 0 or begindex < 0: self.__targetSearchStart = self.SendScintilla( @@ -1012,7 +1010,7 @@ self.SendScintilla(QsciScintilla.SCI_INDICSETSTYLE, indicator, style) self.SendScintilla(QsciScintilla.SCI_INDICSETFORE, indicator, color) - try: + with contextlib.suppress(AttributeError): self.SendScintilla(QsciScintilla.SCI_INDICSETALPHA, indicator, color.alpha()) if style in ( @@ -1022,8 +1020,6 @@ # set outline alpha less transparent self.SendScintilla(QsciScintilla.SCI_INDICSETOUTLINEALPHA, indicator, color.alpha() + 20) - except AttributeError: - pass def setCurrentIndicator(self, indicator): """
--- a/eric6/QScintilla/SearchReplaceWidget.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/SearchReplaceWidget.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import re +import contextlib from PyQt5.QtCore import pyqtSignal, Qt, pyqtSlot, QEvent from PyQt5.QtGui import QColor, QPalette @@ -624,11 +625,9 @@ if indicate: aw.setSearchIndicator(tgtPos, tgtLen) ok = aw.findNextTarget() - try: + with contextlib.suppress(AttributeError): aw.updateMarkerMap() - except AttributeError: - # MiniEditor doesn't have this, ignore it - pass + # ignore it for MiniEditor def __findNextPrev(self, txt, backwards): """
--- a/eric6/QScintilla/Shell.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/Shell.py Thu Apr 15 18:11:24 2021 +0200 @@ -484,16 +484,13 @@ if Preferences.getEditor("ShowWhitespace"): self.setWhitespaceVisibility( QsciScintilla.WhitespaceVisibility.WsVisible) - try: + with contextlib.suppress(AttributeError): self.setWhitespaceForegroundColor( Preferences.getEditorColour("WhitespaceForeground")) self.setWhitespaceBackgroundColor( Preferences.getEditorColour("WhitespaceBackground")) self.setWhitespaceSize( Preferences.getEditor("WhitespaceSize")) - except AttributeError: - # QScintilla before 2.5 doesn't support this - pass else: self.setWhitespaceVisibility( QsciScintilla.WhitespaceVisibility.WsInvisible) @@ -2227,14 +2224,12 @@ self.vm.searchPrevAct.shortcut(), self, self.__searchPrev, self.__searchPrev) - try: + with contextlib.suppress(AttributeError): self.vm.editActGrp.setEnabled(False) self.vm.editorActGrp.setEnabled(True) self.vm.copyActGrp.setEnabled(True) self.vm.viewActGrp.setEnabled(True) self.vm.searchActGrp.setEnabled(False) - except AttributeError: - pass if not self.__windowed: self.__searchShortcut.setEnabled(True) self.__searchNextShortcut.setEnabled(True) @@ -2250,10 +2245,8 @@ @param event the event object (QFocusEvent) """ - try: + with contextlib.suppress(AttributeError): self.vm.editorActGrp.setEnabled(False) - except AttributeError: - pass if not self.__windowed: self.__searchShortcut.setEnabled(False) self.__searchNextShortcut.setEnabled(False)
--- a/eric6/QScintilla/SpellChecker.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/QScintilla/SpellChecker.py Thu Apr 15 18:11:24 2021 +0200 @@ -10,16 +10,15 @@ """ import os +import contextlib from PyQt5.QtCore import QTimer, QObject import Preferences import Utilities -try: +with contextlib.suppress(ImportError, AttributeError, OSError): import enchant -except (ImportError, AttributeError, OSError): - pass class SpellChecker(QObject): @@ -66,10 +65,8 @@ @return list of available languages (list of strings) """ - try: + with contextlib.suppress(NameError): return enchant.list_languages() - except NameError: - pass return [] @classmethod @@ -80,10 +77,8 @@ @return flag indicating availability (boolean) """ if Preferences.getEditor("SpellCheckingEnabled"): - try: + with contextlib.suppress(NameError, AttributeError): return len(enchant.list_languages()) > 0 - except (NameError, AttributeError): - pass return False @classmethod @@ -433,11 +428,8 @@ suggestions = [] spell = self._spelling_dict if spell and len(word) >= self.minimumWordSize: - try: + with contextlib.suppress(enchant.errors.Error): suggestions = spell.suggest(word) - except enchant.errors.Error: - # ignore these - pass return suggestions def add(self, word=None): @@ -529,12 +521,9 @@ (wordEnd - wordStart) >= self.minimumWordSize and self.__checkRegion(wordStart) ): - try: + with contextlib.suppress(enchant.errors.Error): if spell.check(word): continue - except enchant.errors.Error: - # ignore these - pass if word in self.__ignoreWords: continue self.word = word
--- a/eric6/Tools/TRPreviewer.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Tools/TRPreviewer.py Thu Apr 15 18:11:24 2021 +0200 @@ -823,12 +823,10 @@ @return flag indicating if event was filtered out """ if obj in self.widgets and ev.type() == QEvent.Type.Close: - try: + with contextlib.suppress(ValueError): self.widgets.remove(obj) if len(self.widgets) == 0: self.lastWidgetClosed.emit() - except ValueError: - pass return QMdiArea.eventFilter(self, obj, ev)
--- a/eric6/Tools/TrayStarter.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Tools/TrayStarter.py Thu Apr 15 18:11:24 2021 +0200 @@ -9,6 +9,7 @@ import sys import os +import contextlib from PyQt5.QtCore import QProcess, QSettings, QFileInfo from PyQt5.QtGui import QCursor @@ -554,15 +555,13 @@ """<tr><td><b>QScintilla</b></td><td>{0}</td></tr>""" .format(QSCINTILLA_VERSION_STR) ) - try: + with contextlib.suppress(ImportError): from WebBrowser.Tools import WebBrowserTools chromeVersion = WebBrowserTools.getWebEngineVersions()[0] versionText += ( """<tr><td><b>WebEngine</b></td><td>{0}</td></tr>""" .format(chromeVersion) ) - except ImportError: - pass versionText += ( """<tr><td><b>{0}</b></td><td>{1}</td></tr>""" .format(Program, Version)
--- a/eric6/Tools/UIPreviewer.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Tools/UIPreviewer.py Thu Apr 15 18:11:24 2021 +0200 @@ -382,10 +382,8 @@ lst = self.mainWidget.findChildren(QWidget) for obj in lst: - try: + with contextlib.suppress(AttributeError): obj.setStyle(qstyle) - except AttributeError: - pass del lst self.mainWidget.hide()
--- a/eric6/Tools/webBrowserSupport.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Tools/webBrowserSupport.py Thu Apr 15 18:11:24 2021 +0200 @@ -12,14 +12,13 @@ """ import sys +import contextlib variant = "None" -try: +with contextlib.suppress(ImportError): from PyQt5 import QtWebEngineWidgets # __IGNORE_WARNING__ variant = "QtWebEngine" -except ImportError: - pass print(variant) # __IGNORE_WARNING_M801__
--- a/eric6/UI/BrowserModel.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/UI/BrowserModel.py Thu Apr 15 18:11:24 2021 +0200 @@ -10,6 +10,7 @@ import os import fnmatch import json +import contextlib from PyQt5.QtCore import ( QDir, QModelIndex, QAbstractItemModel, QFileSystemWatcher, Qt, QProcess, @@ -648,12 +649,10 @@ # special treatment done later continue cl = dictionary[key] - try: + with contextlib.suppress(AttributeError): if cl.module == moduleName: node = BrowserClassItem(parentItem, cl, fileName) self._addItem(node, parentItem) - except AttributeError: - pass if "@@Coding@@" in keys and Preferences.getUI("BrowserShowCoding"): node = BrowserCodingItem( parentItem,
--- a/eric6/UI/CodeDocumentationViewer.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/UI/CodeDocumentationViewer.py Thu Apr 15 18:11:24 2021 +0200 @@ -84,13 +84,9 @@ ) self.__contents = QWebEngineView(self) self.__contents.page().linkHovered.connect(self.__showLink) - try: - self.__contents.settings().setAttribute( - QWebEngineSettings.WebAttribute.FocusOnNavigationEnabled, - False) - except AttributeError: - # pre Qt 5.8 - pass + self.__contents.settings().setAttribute( + QWebEngineSettings.WebAttribute.FocusOnNavigationEnabled, + False) self.__viewerType = "QWebEngineView" except ImportError: self.__contents = QTextBrowser(self)
--- a/eric6/UI/DiffDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/UI/DiffDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -9,6 +9,8 @@ import os import time +import contextlib +from difflib import unified_diff, context_diff from PyQt5.QtCore import QFileInfo, QEvent, pyqtSlot from PyQt5.QtGui import QTextCursor @@ -24,8 +26,6 @@ import Utilities import Preferences -from difflib import unified_diff, context_diff - class DiffDialog(QWidget, Ui_DiffDialog): """ @@ -132,11 +132,9 @@ txt = self.contents.toPlainText() try: - with open(fname, "w", encoding="utf-8") as f: - try: - f.write(txt) - except UnicodeError: - pass + with open(fname, "w", encoding="utf-8") as f, \ + contextlib.suppress(UnicodeError): + f.write(txt) except OSError as why: E5MessageBox.critical( self, self.tr('Save Diff'),
--- a/eric6/UI/ErrorLogDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/UI/ErrorLogDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import pyqtSlot, Qt from PyQt5.QtWidgets import QDialog, QStyle @@ -49,12 +50,10 @@ self.__ui = parent self.__logFile = logFile - try: + with contextlib.suppress(OSError): with open(logFile, "r", encoding="utf-8") as f: txt = f.read() self.logEdit.setPlainText(txt) - except OSError: - pass @pyqtSlot() def on_emailButton_clicked(self):
--- a/eric6/UI/NotificationWidget.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/UI/NotificationWidget.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ from enum import Enum +import contextlib from PyQt5.QtCore import Qt, QTimer, QPoint from PyQt5.QtWidgets import QFrame, QWidget, QVBoxLayout @@ -237,12 +238,9 @@ # delete the notification index = self.__layout.indexOf(notification) self.__layout.takeAt(index) - try: + with contextlib.suppress(ValueError): self.__notifications.remove(notification) notification.deleteLater() - except ValueError: - # it was already delete by other method; ignore - pass if self.__layout.count(): self.__adjustSizeAndPosition()
--- a/eric6/UI/Previewers/PreviewerHTML.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/UI/Previewers/PreviewerHTML.py Thu Apr 15 18:11:24 2021 +0200 @@ -14,6 +14,7 @@ import tempfile import sys import io +import contextlib from PyQt5.QtCore import pyqtSlot, pyqtSignal, Qt, QUrl, QThread from PyQt5.QtGui import QCursor @@ -697,7 +698,7 @@ pyMdown = False if usePyMdownExtensions: - try: + with contextlib.suppress(ImportError): import pymdownx # __IGNORE_EXCEPTION__ __IGNORE_WARNING__ # PyPI package is 'pymdown-extensions' @@ -708,8 +709,6 @@ 'pymdownx.tasklist', 'pymdownx.smartsymbols', ]) pyMdown = True - except ImportError: - pass if not pyMdown: extensions.extend(['extra', 'toc'])
--- a/eric6/UI/UserInterface.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/UI/UserInterface.py Thu Apr 15 18:11:24 2021 +0200 @@ -1477,7 +1477,7 @@ "eric6installpip.json") if os.path.exists(filename): # eric was installed via pip (i.e. eric-ide) - try: + with contextlib.suppress(OSError): installDateTime = datetime.datetime.now(tz=None) with open(filename, "r") as infoFile: installInfo = json.load(infoFile) @@ -1497,9 +1497,6 @@ installInfo["eric"], os.W_OK) with open(installInfoFile, "w") as infoFile: json.dump(installInfo, infoFile, indent=2) - except OSError: - # ignore this - pass else: changed = False with open(installInfoFile, "r") as infoFile: @@ -3758,34 +3755,28 @@ versionText += ( """<tr><td><b>PyQt</b></td><td>{0}</td></tr>""" ).format(PYQT_VERSION_STR) - try: + with contextlib.suppress(ImportError, AttributeError): from PyQt5 import QtChart versionText += ( """<tr><td><b>PyQtChart</b></td><td>{0}</td></tr>""" ).format(QtChart.PYQT_CHART_VERSION_STR) - except (ImportError, AttributeError): - pass - try: + with contextlib.suppress(ImportError, AttributeError): from PyQt5 import QtWebEngine versionText += ( """<tr><td><b>PyQtWebEngine</b></td><td>{0}</td></tr>""" ).format(QtWebEngine.PYQT_WEBENGINE_VERSION_STR) - except (ImportError, AttributeError): - pass versionText += ( """<tr><td><b>QScintilla</b></td><td>{0}</td></tr>""" ).format(QSCINTILLA_VERSION_STR) versionText += ( """<tr><td><b>sip</b></td><td>{0}</td></tr>""" ).format(sip_version_str) - try: + with contextlib.suppress(ImportError): from WebBrowser.Tools import WebBrowserTools chromeVersion = WebBrowserTools.getWebEngineVersions()[0] versionText += ( """<tr><td><b>WebEngine</b></td><td>{0}</td></tr>""" ).format(chromeVersion) - except ImportError: - pass versionText += ("""<tr><td><b>{0}</b></td><td>{1}</td></tr>""" ).format(Program, Version) versionText += self.tr("""</table>""") @@ -4101,12 +4092,9 @@ """ toolbars = [] for tbName in self.__toolbars: - try: + with contextlib.suppress(IndexError): if self.__toolbars[tbName][2] == category: toolbars.append(self.__toolbars[tbName][1]) - except IndexError: - # backward compatibility; category is not yet supported - pass return toolbars
--- a/eric6/Utilities/BackgroundClient.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Utilities/BackgroundClient.py Thu Apr 15 18:11:24 2021 +0200 @@ -61,12 +61,10 @@ try: importedModule = __import__(module, globals(), locals(), [], 0) self.services[fn] = importedModule.initService() - try: + with contextlib.suppress(AttributeError): self.batchServices["batch_" + fn] = ( importedModule.initBatchService() ) - except AttributeError: - pass return 'ok' except ImportError: return 'Import Error'
--- a/eric6/Utilities/BackgroundService.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Utilities/BackgroundService.py Thu Apr 15 18:11:24 2021 +0200 @@ -13,6 +13,7 @@ import struct import sys from zlib import adler32 +import contextlib from PyQt5.QtCore import QProcess, pyqtSignal, QTimer from PyQt5.QtWidgets import QApplication @@ -215,14 +216,11 @@ self.enqueueRequest(*self.runningJob) else: fx, lng, fn, data = self.runningJob - try: + with contextlib.suppress(KeyError, TypeError): self.services[(fx, lng)][3](fx, lng, fn, self.tr( "An error in Eric's background client stopped the" " service.") ) - except (KeyError, TypeError): - # ignore silently - pass if res != E5MessageBox.No: self.isWorking = None self.restartService(lang, True)
--- a/eric6/Utilities/ModuleParser.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Utilities/ModuleParser.py Thu Apr 15 18:11:24 2021 +0200 @@ -1606,11 +1606,9 @@ return _modules[modname] mod = Module(modname, file, moduleType) - try: + with contextlib.suppress(UnicodeError, OSError): src = Utilities.readEncodedFile(file)[0] mod.scan(src) - except (UnicodeError, OSError): - pass if caching: _modules[modname] = mod return mod
--- a/eric6/Utilities/__init__.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/Utilities/__init__.py Thu Apr 15 18:11:24 2021 +0200 @@ -221,7 +221,7 @@ @param text byte text to decode (bytes) @return tuple of decoded text and encoding (string, string) """ - try: + with contextlib.suppress(UnicodeError, LookupError): if text.startswith(BOM_UTF8): # UTF-8 with BOM return str(text[len(BOM_UTF8):], 'utf-8'), 'utf-8-bom' @@ -234,14 +234,10 @@ coding = get_codingBytes(text) if coding: return str(text, coding), coding - except (UnicodeError, LookupError): - pass # Assume UTF-8 - try: + with contextlib.suppress(UnicodeError, LookupError): return str(text, 'utf-8'), 'utf-8-guessed' - except (UnicodeError, LookupError): - pass guess = None if Preferences.getEditor("AdvancedEncodingDetection"): @@ -262,11 +258,9 @@ pass # Try default encoding - try: + with contextlib.suppress(UnicodeError, LookupError): codec = Preferences.getEditor("DefaultEncoding") return str(text, codec), '{0}-default'.format(codec) - except (UnicodeError, LookupError): - pass if ( Preferences.getEditor("AdvancedEncodingDetection") and @@ -274,11 +268,9 @@ guess['encoding'] is not None ): # Use the guessed one even if confidence level is low - try: + with contextlib.suppress(UnicodeError, LookupError): codec = guess['encoding'].lower() return str(text, codec), '{0}-guessed'.format(codec) - except (UnicodeError, LookupError): - pass # Assume UTF-8 loosing information return str(text, "utf-8", "ignore"), 'utf-8-ignore' @@ -295,16 +287,14 @@ with open(filename, "rb") as f: text = f.read() if encoding: - try: + with contextlib.suppress(UnicodeError, LookupError): return str(text, encoding), '{0}-selected'.format(encoding) - except (UnicodeError, LookupError): - pass + # Try default encoding - try: + with contextlib.suppress(UnicodeError, LookupError): codec = Preferences.getEditor("DefaultEncoding") return str(text, codec), '{0}-default'.format(codec) - except (UnicodeError, LookupError): - pass + # Assume UTF-8 loosing information return str(text, "utf-8", "ignore"), 'utf-8-ignore' else: @@ -364,12 +354,10 @@ raise CodingError(coding) else: if forcedEncoding: - try: + with contextlib.suppress(UnicodeError, LookupError): etext, encoding = ( text.encode(forcedEncoding), forcedEncoding) - except (UnicodeError, LookupError): - # Error: Forced encoding is incorrect, ignore it - pass + # if forced encoding is incorrect, ignore it if encoding is None: # Try the original encoding @@ -382,25 +370,19 @@ .replace("-guessed", "") .replace("-ignore", "") ) - try: + with contextlib.suppress(UnicodeError, LookupError): etext, encoding = text.encode(coding), coding - except (UnicodeError, LookupError): - pass if encoding is None: # Try configured default - try: + with contextlib.suppress(UnicodeError, LookupError): codec = Preferences.getEditor("DefaultEncoding") etext, encoding = text.encode(codec), codec - except (UnicodeError, LookupError): - pass if encoding is None: # Try saving as ASCII - try: + with contextlib.suppress(UnicodeError): etext, encoding = text.encode('ascii'), 'ascii' - except UnicodeError: - pass if encoding is None: # Save as UTF-8 without BOM @@ -438,7 +420,7 @@ @return decoded text (string) """ # try UTF with BOM - try: + with contextlib.suppress(UnicodeError, LookupError): if buffer.startswith(BOM_UTF8): # UTF-8 with BOM return str(buffer[len(BOM_UTF8):], encoding='utf-8') @@ -448,14 +430,10 @@ elif buffer.startswith(BOM_UTF32): # UTF-32 with BOM return str(buffer[len(BOM_UTF32):], encoding='utf-32') - except (UnicodeError, LookupError): - pass # try UTF-8 - try: + with contextlib.suppress(UnicodeError): return str(buffer, encoding="utf-8") - except UnicodeError: - pass # try codec detection try: @@ -1287,7 +1265,7 @@ else: # we are on a Linux or macOS platform for mountCommand in ["mount", "/sbin/mount", "/usr/sbin/mount"]: - try: + with contextlib.suppress(FileNotFoundError): mountOutput = ( subprocess.check_output(mountCommand).splitlines() # secok ) @@ -1308,8 +1286,6 @@ break if volumeDirectory: break - except FileNotFoundError: - pass if findAll: return volumeDirectories @@ -1892,13 +1868,11 @@ info.append(" PyQtWebEngine not installed") info.append(" QScintilla {0}".format(QSCINTILLA_VERSION_STR)) info.append(" sip {0}".format(sip_version_str)) - try: + with contextlib.suppress(ImportError): from PyQt5 import QtWebEngineWidgets # __IGNORE_WARNING__ from WebBrowser.Tools import WebBrowserTools chromeVersion = WebBrowserTools.getWebEngineVersions()[0] info.append(" WebEngine {0}".format(chromeVersion)) - except ImportError: - pass info.append(" {0} {1}".format(Program, Version)) info.append("") info.append("Platform: {0}".format(sys.platform)) @@ -1923,7 +1897,7 @@ info = [] app = e5App() if app is not None: - try: + with contextlib.suppress(KeyError): pm = app.getObject("PluginManager") versions = {} for pinfo in pm.getPluginInfos(): @@ -1933,8 +1907,6 @@ for pluginModuleName in sorted(versions.keys()): info.append(" {0} {1}".format( pluginModuleName, versions[pluginModuleName])) - except KeyError: - pass return linesep.join(info) @@ -2007,13 +1979,10 @@ if finished and proc.exitCode() == 0: text = proc.readAllStandardOutput() sysPathResult = str(text, "utf-8", "replace").strip() - try: + with contextlib.suppress(TypeError, ValueError): sysPath = json.loads(sysPathResult) if "" in sysPath: sysPath.remove("") - except (TypeError, ValueError): - # ignore faulty results and return empty list - pass return sysPath
--- a/eric6/ViewManager/ViewManager.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/ViewManager/ViewManager.py Thu Apr 15 18:11:24 2021 +0200 @@ -9,6 +9,7 @@ import re import os +import contextlib from PyQt5.QtCore import ( pyqtSignal, pyqtSlot, Qt, QSignalMapper, QTimer, QFileInfo, QPoint, @@ -6285,10 +6286,8 @@ @return flag indicating success (boolean) """ - try: + with contextlib.suppress(TypeError): e5App().focusChanged.disconnect(self.appFocusChanged) - except TypeError: - pass self.closeAllWindows() self.currentEditor = None
--- a/eric6/WebBrowser/AdBlock/AdBlockManager.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/AdBlock/AdBlockManager.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import ( pyqtSignal, QObject, QUrl, QUrlQuery, QFile, QByteArray, QMutex @@ -303,7 +304,7 @@ self.__customSubscriptionUrlString)): return - try: + with contextlib.suppress(ValueError): self.__subscriptions.remove(subscription) rulesFileName = subscription.rulesFileName() QFile.remove(rulesFileName) @@ -312,8 +313,6 @@ self.removeSubscription(requiresSubscription, False) if emitSignal: self.rulesChanged.emit() - except ValueError: - pass def addSubscriptionFromUrl(self, url): """
--- a/eric6/WebBrowser/Bookmarks/BookmarksManager.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/Bookmarks/BookmarksManager.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import os +import contextlib from PyQt5.QtCore import ( pyqtSignal, QT_TRANSLATE_NOOP, QObject, QFile, QIODevice, QXmlStreamReader, @@ -323,12 +324,9 @@ @param node reference to the node to be changed (BookmarkNode) @param count visit count to be set (int or str) """ - try: + with contextlib.suppress(ValueError): node.visitCount = int(count) self.__saveTimer.changeOccurred() - except ValueError: - # ignore invalid values - pass def bookmarks(self): """
--- a/eric6/WebBrowser/Bookmarks/BookmarksModel.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/Bookmarks/BookmarksModel.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing the bookmark model class. """ +import contextlib + from PyQt5.QtCore import ( Qt, QAbstractItemModel, QModelIndex, QUrl, QByteArray, QDataStream, QIODevice, QBuffer, QMimeData @@ -154,10 +156,8 @@ orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole ): - try: + with contextlib.suppress(IndexError): return self.__headers[section] - except IndexError: - pass return QAbstractItemModel.headerData(self, section, orientation, role) def data(self, index, role=Qt.ItemDataRole.DisplayRole):
--- a/eric6/WebBrowser/CookieJar/CookieJar.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/CookieJar/CookieJar.py Thu Apr 15 18:11:24 2021 +0200 @@ -57,11 +57,7 @@ "web_browser", "cookies.ini") self.__store = WebBrowserWindow.webProfile().cookieStore() - try: - self.__store.setCookieFilter(self.__cookieFilter) - except AttributeError: - # pre Qt 5.11 - pass + self.__store.setCookieFilter(self.__cookieFilter) self.__store.cookieAdded.connect(self.__cookieAdded) self.__store.cookieRemoved.connect(self.__cookieRemoved)
--- a/eric6/WebBrowser/FeaturePermissions/FeaturePermissionBar.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/FeaturePermissions/FeaturePermissionBar.py Thu Apr 15 18:11:24 2021 +0200 @@ -55,25 +55,17 @@ self.tr("{0} wants to use your microphone and camera."), QWebEnginePage.Feature.MouseLock: self.tr("{0} wants to lock your mouse."), + QWebEnginePage.Feature.DesktopVideoCapture: + self.tr("{0} wants to capture video of your screen."), + QWebEnginePage.Feature.DesktopAudioVideoCapture: + self.tr("{0} wants to capture audio and video of your" + " screen."), } - try: - # these are defined as of Qt 5.10.0/PyQt 5.10.0 - self.__permissionFeatureTexts.update({ - QWebEnginePage.Feature.DesktopVideoCapture: - self.tr("{0} wants to capture video of your screen."), - QWebEnginePage.Feature.DesktopAudioVideoCapture: - self.tr("{0} wants to capture audio and video of your" - " screen."), - }) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): # this was re-added in Qt 5.13.0 self.__permissionFeatureTexts[ QWebEnginePage.Feature.Notifications] = self.tr( "{0} wants to use desktop notifications.") - except AttributeError: - pass self.__permissionFeatureIconNames = { QWebEnginePage.Feature.Geolocation: "geolocation", @@ -81,23 +73,15 @@ QWebEnginePage.Feature.MediaVideoCapture: "camera", QWebEnginePage.Feature.MediaAudioVideoCapture: "audio-video", QWebEnginePage.Feature.MouseLock: "mouse", + QWebEnginePage.Feature.DesktopVideoCapture: + "desktopVideoCapture", + QWebEnginePage.Feature.DesktopAudioVideoCapture: + "desktopAudioVideoCapture", } - try: - # these are defined as of Qt 5.10.0/PyQt 5.10.0 - self.__permissionFeatureIconNames.update({ - QWebEnginePage.Feature.DesktopVideoCapture: - "desktopVideoCapture", - QWebEnginePage.Feature.DesktopAudioVideoCapture: - "desktopAudioVideoCapture", - }) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): # this was re-added in Qt 5.13.0 self.__permissionFeatureIconNames[ QWebEnginePage.Feature.Notifications] = "notification" - except AttributeError: - pass self.setAutoFillBackground(True) self.__layout = QHBoxLayout()
--- a/eric6/WebBrowser/FeaturePermissions/FeaturePermissionManager.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/FeaturePermissions/FeaturePermissionManager.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing the feature permission manager object. """ +import contextlib + from PyQt5.QtCore import QObject from PyQt5.QtWidgets import QDialog from PyQt5.QtWebEngineWidgets import QWebEnginePage @@ -51,33 +53,25 @@ QWebEnginePage.PermissionPolicy.PermissionGrantedByUser: [], QWebEnginePage.PermissionPolicy.PermissionDeniedByUser: [], }, + QWebEnginePage.Feature.DesktopVideoCapture: { + QWebEnginePage.PermissionPolicy.PermissionGrantedByUser: + [], + QWebEnginePage.PermissionPolicy.PermissionDeniedByUser: + [], + }, + QWebEnginePage.Feature.DesktopAudioVideoCapture: { + QWebEnginePage.PermissionPolicy.PermissionGrantedByUser: + [], + QWebEnginePage.PermissionPolicy.PermissionDeniedByUser: + [], + }, } - try: - # these are defined as of Qt 5.10.0/PyQt 5.10.0 - self.__featurePermissions.update({ - QWebEnginePage.Feature.DesktopVideoCapture: { - QWebEnginePage.PermissionPolicy.PermissionGrantedByUser: - [], - QWebEnginePage.PermissionPolicy.PermissionDeniedByUser: - [], - }, - QWebEnginePage.Feature.DesktopAudioVideoCapture: { - QWebEnginePage.PermissionPolicy.PermissionGrantedByUser: - [], - QWebEnginePage.PermissionPolicy.PermissionDeniedByUser: - [], - }, - }) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): # this was re-added in Qt 5.13.0 self.__featurePermissions[QWebEnginePage.Feature.Notifications] = { QWebEnginePage.PermissionPolicy.PermissionGrantedByUser: [], QWebEnginePage.PermissionPolicy.PermissionDeniedByUser: [], } - except AttributeError: - pass self.__featurePermissionsKeys = { (QWebEnginePage.Feature.Geolocation, @@ -110,26 +104,20 @@ (QWebEnginePage.Feature.MouseLock, QWebEnginePage.PermissionPolicy.PermissionDeniedByUser): "MouseLockDenied", + (QWebEnginePage.Feature.DesktopVideoCapture, + QWebEnginePage.PermissionPolicy.PermissionGrantedByUser): + "DesktopVideoCaptureGranted", + (QWebEnginePage.Feature.DesktopVideoCapture, + QWebEnginePage.PermissionPolicy.PermissionDeniedByUser): + "DesktopVideoCaptureDenied", + (QWebEnginePage.Feature.DesktopAudioVideoCapture, + QWebEnginePage.PermissionPolicy.PermissionGrantedByUser): + "DesktopAudioVideoCaptureGranted", + (QWebEnginePage.Feature.DesktopAudioVideoCapture, + QWebEnginePage.PermissionPolicy.PermissionDeniedByUser): + "DesktopAudioVideoCaptureDenied", } - try: - # these are defined as of Qt 5.10.0/PyQt 5.10.0 - self.__featurePermissionsKeys.update({ - (QWebEnginePage.Feature.DesktopVideoCapture, - QWebEnginePage.PermissionPolicy.PermissionGrantedByUser): - "DesktopVideoCaptureGranted", - (QWebEnginePage.Feature.DesktopVideoCapture, - QWebEnginePage.PermissionPolicy.PermissionDeniedByUser): - "DesktopVideoCaptureDenied", - (QWebEnginePage.Feature.DesktopAudioVideoCapture, - QWebEnginePage.PermissionPolicy.PermissionGrantedByUser): - "DesktopAudioVideoCaptureGranted", - (QWebEnginePage.Feature.DesktopAudioVideoCapture, - QWebEnginePage.PermissionPolicy.PermissionDeniedByUser): - "DesktopAudioVideoCaptureDenied", - }) - except AttributeError: - pass - try: + with contextlib.suppress(AttributeError): # this was re-added in Qt 5.13.0 self.__featurePermissionsKeys.update({ (QWebEnginePage.Feature.Notifications, @@ -139,8 +127,6 @@ QWebEnginePage.PermissionPolicy.PermissionDeniedByUser): "NotificationsDenied", }) - except AttributeError: - pass self.__loaded = False
--- a/eric6/WebBrowser/History/HistoryModel.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/History/HistoryModel.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing the history model. """ +import contextlib + from PyQt5.QtCore import Qt, QAbstractTableModel, QModelIndex, QUrl import WebBrowser.WebBrowserWindow @@ -84,10 +86,8 @@ orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole ): - try: + with contextlib.suppress(IndexError): return self.__headers[section] - except IndexError: - pass return QAbstractTableModel.headerData(self, section, orientation, role) def data(self, index, role=Qt.ItemDataRole.DisplayRole):
--- a/eric6/WebBrowser/Network/NetworkManager.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/Network/NetworkManager.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import json +import contextlib from PyQt5.QtCore import pyqtSignal, QByteArray from PyQt5.QtWidgets import QStyle, QDialog @@ -123,12 +124,9 @@ dbString = Preferences.getWebBrowser("SslExceptionsDB") if dbString: - try: + with contextlib.suppress(ValueError): db = json.loads(dbString) self.__permanentlyIgnoredSslErrors = db - except ValueError: - # ignore silently - pass self.__loaded = True
--- a/eric6/WebBrowser/Network/ProtocolHandlerManager.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/Network/ProtocolHandlerManager.py Thu Apr 15 18:11:24 2021 +0200 @@ -9,6 +9,7 @@ import os import json +import contextlib from PyQt5.QtCore import QObject, QUrl from PyQt5.QtWebEngineWidgets import QWebEnginePage @@ -97,7 +98,7 @@ """ Private method to load the registered protocol handlers. """ - try: + with contextlib.suppress(OSError): with open(self.__protocolHandlersFileName(), "r") as protocolHandlersFile: protocolHandlersData = json.load(protocolHandlersFile) @@ -108,9 +109,6 @@ url = QUrl(urlStr) self.__protocolHandlers[scheme] = url self.__registerHandler(scheme, url) - except OSError: - # ignore issues silently - pass def __save(self): """ @@ -136,12 +134,8 @@ page = QWebEnginePage(self) page.loadFinished.connect(page.deleteLater) - try: - # for Qt >= 5.11 - page.registerProtocolHandlerRequested.connect( - lambda r: r.accept()) - except AttributeError: - pass + page.registerProtocolHandlerRequested.connect( + lambda r: r.accept()) page.setHtml( "<script>navigator.registerProtocolHandler('{0}', '{1}', '')" "</script>".format(scheme, urlStr),
--- a/eric6/WebBrowser/Network/SslErrorExceptionsDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/Network/SslErrorExceptionsDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -68,28 +68,14 @@ .CertificateNameConstraintViolation: self.tr("The certificate claimed DNS names that are in" " violation of name constraints."), + QWebEngineCertificateError.Error.CertificateValidityTooLong: + self.tr("The certificate has a validity period that is" + " too long."), + QWebEngineCertificateError.Error.CertificateTransparencyRequired: + self.tr("Certificate Transparency was required for this" + " connection, but the server did not provide" + " information that complied with the policy."), } - try: - self.__errorDescriptions[ - QWebEngineCertificateError.Error.CertificateValidityTooLong - ] = self.tr( - "The certificate has a validity period that is too long." - ) - except AttributeError: - # the value was added in Qt 5.7 - pass - try: - self.__errorDescriptions[ - QWebEngineCertificateError.Error - .CertificateTransparencyRequired - ] = self.tr( - "Certificate Transparency was required for this" - " connection, but the server did not provide" - " information that complied with the policy." - ) - except AttributeError: - # the value was added in Qt 5.8 - pass for host, errors in errorsDict.items(): itm = QTreeWidgetItem(self.errorsTree, [host])
--- a/eric6/WebBrowser/OpenSearch/OpenSearchEngineModel.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/OpenSearch/OpenSearchEngineModel.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import re +import contextlib from PyQt5.QtCore import Qt, QUrl, QAbstractTableModel, QModelIndex from PyQt5.QtGui import QPixmap, QIcon @@ -199,10 +200,8 @@ orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole ): - try: + with contextlib.suppress(IndexError): return self.__headers[section] - except IndexError: - pass return None
--- a/eric6/WebBrowser/Passwords/PasswordModel.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/Passwords/PasswordModel.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a model for password management. """ +import contextlib + from PyQt5.QtCore import Qt, QModelIndex, QAbstractTableModel @@ -153,9 +155,7 @@ orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole ): - try: + with contextlib.suppress(IndexError): return self.__headers[section] - except IndexError: - pass return None
--- a/eric6/WebBrowser/QtHelp/QtHelpDocumentationDialog.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/QtHelp/QtHelpDocumentationDialog.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import sqlite3 +import contextlib from PyQt5.QtCore import pyqtSlot, Qt, QItemSelectionModel from PyQt5.QtWidgets import ( @@ -477,10 +478,8 @@ """ Private method to remove attributes from the Qt Help database. """ - try: + with contextlib.suppress(sqlite3.DatabaseError): self.__db = sqlite3.connect(self.__engine.collectionFile()) - except sqlite3.DatabaseError: - pass # ignore database errors for attr in self.__removedAttributes: self.__db.execute(
--- a/eric6/WebBrowser/Session/SessionManager.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/Session/SessionManager.py Thu Apr 15 18:11:24 2021 +0200 @@ -10,6 +10,7 @@ import os import json import functools +import contextlib from PyQt5.QtCore import ( pyqtSlot, pyqtSignal, Qt, QObject, QTimer, QDir, QFile, QFileInfo, @@ -466,14 +467,11 @@ if "CurrentWindowIndex" in sessionData: currentWindowIndex = sessionData["CurrentWindowIndex"] - try: + with contextlib.suppress(IndexError): currentWindow = ( WebBrowserWindow.mainWindows()[currentWindowIndex] ) QTimer.singleShot(0, lambda: currentWindow.raise_()) - except IndexError: - # ignore it - pass def renameSession(self, sessionFilePath, flags=0): """
--- a/eric6/WebBrowser/Sync/FtpSyncHandler.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/Sync/FtpSyncHandler.py Thu Apr 15 18:11:24 2021 +0200 @@ -9,6 +9,7 @@ import ftplib # secok import io +import contextlib from PyQt5.QtCore import ( pyqtSignal, QTimer, QFileInfo, QCoreApplication, QByteArray @@ -393,11 +394,9 @@ if self.__idleTimer.isActive(): self.__idleTimer.stop() - try: + with contextlib.suppress(ftplib.all_errors): if self.__connected: self.__ftp.quit() - except ftplib.all_errors: - pass # ignore FTP errors because we are shutting down anyway self.__connected = False def __idleTimeout(self):
--- a/eric6/WebBrowser/UserAgent/UserAgentModel.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/UserAgent/UserAgentModel.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a model for user agent management. """ +import contextlib + from PyQt5.QtCore import Qt, QModelIndex, QAbstractTableModel @@ -129,9 +131,7 @@ orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole ): - try: + with contextlib.suppress(IndexError): return self.__headers[section] - except IndexError: - pass return None
--- a/eric6/WebBrowser/WebBrowserPage.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/WebBrowserPage.py Thu Apr 15 18:11:24 2021 +0200 @@ -92,13 +92,8 @@ self.fullScreenRequested.connect(self.__fullScreenRequested) self.urlChanged.connect(self.__urlChanged) self.contentsSizeChanged.connect(self.__contentsSizeChanged) - - try: - self.registerProtocolHandlerRequested.connect( - self.__registerProtocolHandlerRequested) - except AttributeError: - # defined for Qt >= 5.11 - pass + self.registerProtocolHandlerRequested.connect( + self.__registerProtocolHandlerRequested) self.__sslConfiguration = None @@ -578,29 +573,25 @@ ## Methods below implement protocol handler related functions ############################################################# - try: - @pyqtSlot("QWebEngineRegisterProtocolHandlerRequest") - def __registerProtocolHandlerRequested(self, request): - """ - Private slot to handle the registration of a custom protocol - handler. - - @param request reference to the registration request - @type QWebEngineRegisterProtocolHandlerRequest - """ - from PyQt5.QtWebEngineCore import ( - QWebEngineRegisterProtocolHandlerRequest - ) - - if self.__registerProtocolHandlerRequest: - del self.__registerProtocolHandlerRequest - self.__registerProtocolHandlerRequest = None - self.__registerProtocolHandlerRequest = ( - QWebEngineRegisterProtocolHandlerRequest(request) - ) - except TypeError: - # this is supported with Qt 5.12 and later - pass + @pyqtSlot("QWebEngineRegisterProtocolHandlerRequest") + def __registerProtocolHandlerRequested(self, request): + """ + Private slot to handle the registration of a custom protocol + handler. + + @param request reference to the registration request + @type QWebEngineRegisterProtocolHandlerRequest + """ + from PyQt5.QtWebEngineCore import ( + QWebEngineRegisterProtocolHandlerRequest + ) + + if self.__registerProtocolHandlerRequest: + del self.__registerProtocolHandlerRequest + self.__registerProtocolHandlerRequest = None + self.__registerProtocolHandlerRequest = ( + QWebEngineRegisterProtocolHandlerRequest(request) + ) def registerProtocolHandlerRequestUrl(self): """
--- a/eric6/WebBrowser/WebBrowserTabWidget.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/WebBrowserTabWidget.py Thu Apr 15 18:11:24 2021 +0200 @@ -445,12 +445,8 @@ browser.page().recentlyAudibleChanged.connect( lambda audible: self.__recentlyAudibleChanged( audible, browser.page())) - try: - browser.page().printRequested.connect( - lambda: self.printBrowser(browser)) - except AttributeError: - # pre Qt 5.12 - pass + browser.page().printRequested.connect( + lambda: self.printBrowser(browser)) browser.showMessage.connect(self.showMessage) if position == -1:
--- a/eric6/WebBrowser/WebBrowserView.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/WebBrowserView.py Thu Apr 15 18:11:24 2021 +0200 @@ -10,6 +10,7 @@ import os import functools +import contextlib from PyQt5.QtCore import ( pyqtSignal, pyqtSlot, Qt, QUrl, QFileInfo, QTimer, QEvent, QPoint, @@ -149,28 +150,18 @@ self.__page.safeBrowsingAbort.connect(self.safeBrowsingAbort) self.__page.safeBrowsingBad.connect(self.safeBrowsingBad) self.__page.printPageRequested.connect(self.__printPage) - try: - self.__page.quotaRequested.connect(self.__quotaRequested) - # The registerProtocolHandlerRequested signal is handled in - # WebBrowserPage. - except AttributeError: - # pre Qt 5.11 - pass - try: - self.__page.selectClientCertificate.connect( - self.__selectClientCertificate) - except AttributeError: - # pre Qt 5.12 - pass - try: + self.__page.quotaRequested.connect(self.__quotaRequested) + # The registerProtocolHandlerRequested signal is handled in + # WebBrowserPage. + self.__page.selectClientCertificate.connect( + self.__selectClientCertificate) + with contextlib.suppress(AttributeError, ImportError): + #- Qt >= 5.14 from PyQt5.QtWebEngineCore import QWebEngineFindTextResult # __IGNORE_WARNING__ self.__page.findTextFinished.connect( self.__findTextFinished) - except (AttributeError, ImportError): - # pre Qt 5.14 - pass def __setRwhvqt(self): """ @@ -1680,14 +1671,11 @@ self.__siteIconLoader.deleteLater() self.__siteIconLoader = WebIconLoader(url, self) self.__siteIconLoader.iconLoaded.connect(self.__iconLoaded) - try: + with contextlib.suppress(AttributeError): self.__siteIconLoader.sslConfiguration.connect( self.page().setSslConfiguration) self.__siteIconLoader.clearSslConfiguration.connect( self.page().clearSslConfiguration) - except AttributeError: - # no SSL available - pass def __iconLoaded(self, icon): """
--- a/eric6/WebBrowser/WebBrowserWindow.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/WebBrowserWindow.py Thu Apr 15 18:11:24 2021 +0200 @@ -11,6 +11,7 @@ import shutil import sys import functools +import contextlib from PyQt5.QtCore import ( pyqtSlot, pyqtSignal, Qt, QByteArray, QSize, QTimer, QUrl, QProcess, @@ -646,14 +647,12 @@ Preferences.getWebBrowser( "DnsPrefetchEnabled")) - try: + with contextlib.suppress(AttributeError, KeyError): # Qt 5.13 settings.setAttribute( QWebEngineSettings.WebAttribute.PdfViewerEnabled, Preferences.getWebBrowser( "PdfViewerEnabled")) - except (AttributeError, KeyError): - pass def __initActions(self): """ @@ -2805,7 +2804,7 @@ else: Preferences.setGeometry("WebBrowserGeometry", QByteArray()) - try: + with contextlib.suppress(ValueError): browserIndex = WebBrowserWindow.BrowserWindows.index(self) if len(WebBrowserWindow.BrowserWindows) and browserIndex == 0: if len(WebBrowserWindow.BrowserWindows) > 1: @@ -2821,8 +2820,6 @@ QDesktopServices.unsetUrlHandler("https") if len(WebBrowserWindow.BrowserWindows) > 0: del WebBrowserWindow.BrowserWindows[browserIndex] - except ValueError: - pass Preferences.syncPreferences() if ( @@ -3214,14 +3211,11 @@ QWebEngineProfile.HttpCacheType.MemoryHttpCache) profile.setHttpCacheMaximumSize(0) - try: + with contextlib.suppress(AttributeError): profile.setSpellCheckEnabled( Preferences.getWebBrowser("SpellCheckEnabled")) profile.setSpellCheckLanguages( Preferences.getWebBrowser("SpellCheckLanguages")) - except AttributeError: - # not yet supported - pass self.__virusTotal.preferencesChanged() if ( @@ -4795,14 +4789,11 @@ QWebEngineProfile.PersistentCookiesPolicy .AllowPersistentCookies) - try: + with contextlib.suppress(AttributeError): cls._webProfile.setSpellCheckEnabled( Preferences.getWebBrowser("SpellCheckEnabled")) cls._webProfile.setSpellCheckLanguages( Preferences.getWebBrowser("SpellCheckLanguages")) - except AttributeError: - # not yet supported - pass # Setup QWebChannel user scripts from .WebBrowserPage import WebBrowserPage
--- a/eric6/WebBrowser/ZoomManager/ZoomManager.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/ZoomManager/ZoomManager.py Thu Apr 15 18:11:24 2021 +0200 @@ -8,6 +8,7 @@ """ import json +import contextlib from PyQt5.QtCore import pyqtSignal, QObject @@ -54,12 +55,9 @@ dbString = Preferences.getWebBrowser("ZoomValuesDB") if dbString: - try: + with contextlib.suppress(ValueError): db = json.loads(dbString) self.__zoomDB = db - except ValueError: - # ignore silently - pass self.__loaded = True
--- a/eric6/WebBrowser/ZoomManager/ZoomValuesModel.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/WebBrowser/ZoomManager/ZoomValuesModel.py Thu Apr 15 18:11:24 2021 +0200 @@ -7,6 +7,8 @@ Module implementing a model for zoom values management. """ +import contextlib + from PyQt5.QtCore import Qt, QModelIndex, QAbstractTableModel @@ -129,9 +131,7 @@ orientation == Qt.Orientation.Horizontal and role == Qt.ItemDataRole.DisplayRole ): - try: + with contextlib.suppress(IndexError): return self.__headers[section] - except IndexError: - pass return None
--- a/eric6/eric6.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/eric6.py Thu Apr 15 18:11:24 2021 +0200 @@ -13,6 +13,7 @@ import sys import os +import contextlib originalPathString = os.getenv("PATH") @@ -24,20 +25,17 @@ sys.path.insert(1, os.path.dirname(__file__)) -try: +with contextlib.suppress(AttributeError): try: from PyQt5 import sip # __IGNORE_EXCEPTION__ except ImportError: import sip sip.setdestroyonexit(False) -except AttributeError: - pass import traceback import time import logging import io -import contextlib try: from PyQt5.QtCore import qWarning, QLibraryInfo, QTimer, QCoreApplication
--- a/eric6/eric6_browser.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/eric6_browser.py Thu Apr 15 18:11:24 2021 +0200 @@ -14,17 +14,16 @@ import sys import os +import contextlib sys.path.insert(1, os.path.dirname(__file__)) -try: +with contextlib.suppress(AttributeError): try: from PyQt5 import sip # __IGNORE_EXCEPTION__ except ImportError: import sip sip.setdestroyonexit(False) -except AttributeError: - pass app = None SettingsDir = None
--- a/eric6/eric6_post_install.py Thu Apr 15 16:52:05 2021 +0200 +++ b/eric6/eric6_post_install.py Thu Apr 15 18:11:24 2021 +0200 @@ -12,6 +12,7 @@ import os import shutil import sysconfig +import contextlib ###################################################################### ## Post installation hooks for Windows below @@ -120,16 +121,13 @@ from win32com.client import Dispatch from pywintypes import com_error - try: + with contextlib.suppress(com_error): shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(linkPath) shortcut.Targetpath = targetPath shortcut.WorkingDirectory = os.path.dirname(targetPath) shortcut.IconLocation = iconPath shortcut.save() - except com_error: - # maybe restrictions prohibited link creation - pass def windowsProgramsEntry():
--- a/scripts/create_windows_links.py Thu Apr 15 16:52:05 2021 +0200 +++ b/scripts/create_windows_links.py Thu Apr 15 18:11:24 2021 +0200 @@ -11,6 +11,7 @@ import os import sys +import contextlib from eric6config import getConfig @@ -93,16 +94,13 @@ from win32com.client import Dispatch from pywintypes import com_error - try: + with contextlib.suppress(com_error): shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(linkPath) shortcut.Targetpath = targetPath shortcut.WorkingDirectory = os.path.dirname(targetPath) shortcut.IconLocation = iconPath shortcut.save() - except com_error: - # maybe restrictions prohibited link creation - pass def windowsDesktopNames():
--- a/scripts/install-debugclients.py Thu Apr 15 16:52:05 2021 +0200 +++ b/scripts/install-debugclients.py Thu Apr 15 18:11:24 2021 +0200 @@ -18,6 +18,7 @@ import compileall import shutil import fnmatch +import contextlib # Define the globals. progName = None @@ -41,10 +42,8 @@ global currDir if sys.platform.startswith("win"): - try: + with contextlib.suppress(): input("Press enter to continue...") # secok - except (EOFError, SyntaxError): - pass os.chdir(currDir)
--- a/scripts/install.py Thu Apr 15 16:52:05 2021 +0200 +++ b/scripts/install.py Thu Apr 15 18:11:24 2021 +0200 @@ -100,10 +100,8 @@ print() if sys.platform.startswith(("win", "cygwin")): - try: + with contextlib.suppress(): input("Press enter to continue...") # secok - except (EOFError, SyntaxError): - pass os.chdir(currDir) @@ -558,7 +556,7 @@ os.remove(name) # Cleanup API files - try: + with contextlib.suppress(AttributeError): apidir = getConfig('apidir') for progLanguage in progLanguages: for name in getConfig('apis'): @@ -569,8 +567,6 @@ os.path.join(apidir, progLanguage.lower(), "*.bas")): if os.path.basename(apiname) != "eric6.bas": os.remove(apiname) - except AttributeError: - pass if sys.platform == "darwin": # delete the Mac app bundle @@ -1449,7 +1445,7 @@ from PyQt5.QtCore import qVersion except ImportError as msg: installed = not isSudo and pipInstall( - "PyQt5>=5.12.1,<5.15.2", + "PyQt5>=5.12.1", "'PyQt5' could not be detected.\nError: {0}".format(msg) ) if installed: @@ -1485,7 +1481,7 @@ print("Optional 'PyQtWebEngine' could not be detected.") else: pipInstall( - "PyQtWebEngine>=5.12.1,<5.15.2", + "PyQtWebEngine>=5.12.1", "Optional 'PyQtWebEngine' could not be detected.\n" "Error: {0}".format(msg) ) @@ -1497,7 +1493,7 @@ print("Optional 'PyQtChart' could not be detected.") else: pipInstall( - "PyQtChart>=5.12.1,<5.15.2", + "PyQtChart>=5.12.1", "Optional 'PyQtChart' could not be detected.\n" "Error: {0}".format(msg) ) @@ -1565,13 +1561,11 @@ modulesOK = False for altModule in altModules: name = altModule.split(".")[1] - try: + with contextlib.suppress(ImportError): __import__(altModule) print("Found", name) modulesOK = True break - except ImportError: - pass if not modulesOK and not forcedOk: altModulesOK = False print('Sorry, please install {0}.' @@ -1611,7 +1605,7 @@ exit(2) # check version of sip - try: + with contextlib.suppress(ImportError, AttributeError): try: from PyQt5 import sip except ImportError: @@ -1627,11 +1621,11 @@ minor = int(minor) pat = int(pat) if ( - major < 4 or - (major == 4 and minor < 14) or - (major == 4 and minor == 14 and pat < 2) + major < 5 or + (major == 5 and minor < 0) or + (major == 5 and minor == 0 and pat < 0) ): - print('Sorry, you must have sip 4.14.2 or higher or' + print('Sorry, you must have sip 5.0.0 or higher or' ' a recent snapshot release.') exit(3) # check for blacklisted versions @@ -1642,8 +1636,6 @@ .format(vers)) print('Please install another version.') exit(3) - except (ImportError, AttributeError): - pass # check version of PyQt from PyQt5.QtCore import PYQT_VERSION_STR @@ -1702,15 +1694,12 @@ exit(5) # print version info for additional modules - try: + with contextlib.suppress(NameError, AttributeError): print("PyQtChart:", QtChart.PYQT_CHART_VERSION_STR) - except (NameError, AttributeError): - pass - try: + + with contextlib.suppress(ImportError, AttributeError): from PyQt5 import QtWebEngine print("PyQtWebEngine.", QtWebEngine.PYQT_WEBENGINE_VERSION_STR) - except (ImportError, AttributeError): - pass print("All dependencies ok.") print() @@ -1807,16 +1796,13 @@ from win32com.client import Dispatch from pywintypes import com_error - try: + with contextlib.suppress(com_error): shell = Dispatch('WScript.Shell') shortcut = shell.CreateShortCut(linkPath) shortcut.Targetpath = targetPath shortcut.WorkingDirectory = os.path.dirname(targetPath) shortcut.IconLocation = iconPath shortcut.save() - except com_error: - # maybe restrictions prohibited link creation - pass def windowsDesktopNames(): @@ -1990,15 +1976,13 @@ createInstallConfig() # get rid of development config file, if it exists - try: + with contextlib.suppress(OSError): if installFromSource: os.rename(configName, configName + ".orig") configNameC = configName + 'c' if os.path.exists(configNameC): os.remove(configNameC) os.remove(configName) - except OSError: - pass # cleanup old installation print("Cleaning up old installation ...")
--- a/scripts/uninstall-debugclients.py Thu Apr 15 16:52:05 2021 +0200 +++ b/scripts/uninstall-debugclients.py Thu Apr 15 18:11:24 2021 +0200 @@ -14,6 +14,7 @@ import os import shutil import distutils.sysconfig +import contextlib # Define the globals. progName = None @@ -32,10 +33,8 @@ global currDir if sys.platform.startswith("win"): - try: + with contextlib.suppress(): input("Press enter to continue...") # secok - except (EOFError, SyntaxError): - pass os.chdir(currDir)
--- a/scripts/uninstall.py Thu Apr 15 16:52:05 2021 +0200 +++ b/scripts/uninstall.py Thu Apr 15 18:11:24 2021 +0200 @@ -15,6 +15,7 @@ import shutil import glob import distutils.sysconfig +import contextlib # Define the globals. progName = None @@ -42,10 +43,8 @@ os.rename("eric6config.py.orig", "eric6config.py") if sys.platform.startswith(("win", "cygwin")): - try: + with contextlib.suppress(): input("Press enter to continue...") # secok - except (EOFError, SyntaxError): - pass os.chdir(currDir)
--- a/setup.py Thu Apr 15 16:52:05 2021 +0200 +++ b/setup.py Thu Apr 15 18:11:24 2021 +0200 @@ -395,8 +395,6 @@ # cleanup for fileName in [infoFileName, appdataFileName]: if os.path.exists(fileName + ".orig"): - try: + with contextlib.suppress(OSError): os.remove(fileName) os.rename(fileName + ".orig", fileName) - except OSError: - pass