From 34696fbccdd6efea5f94f5d628dbb902d60a046d Mon Sep 17 00:00:00 2001 From: James Butler Date: Sat, 21 May 2022 15:21:45 -0400 Subject: [PATCH] STYLE: Update python code with statement fixes This fixes many of the pycodestyle E7 statement error codes. Bulk of updates performed using autopep8 CLI with the following command: autopep8 --in-place --select E701,E703,E712,E713,E714,E741 $(git ls-files '*.py') See https://github.com/hhatto/autopep8#readme References: * Multiple statements on one line (colon) See https://www.flake8rules.com/rules/E701.html * Statement ends with a semicolon See https://www.flake8rules.com/rules/E703.html * Comparison to true should be 'if cond is true:' or 'if cond:' See https://www.flake8rules.com/rules/E712.html * Test for membership should be 'not in' See https://www.flake8rules.com/rules/E713.html * Test for object identity should be 'is not' See https://www.flake8rules.com/rules/E714.html * Do not use variables named 'I', 'O', or 'l' See https://www.flake8rules.com/rules/E741.html --- .flake8 | 12 -------- .../Testing/Python/MeasureStartupTimes.py | 30 ++++++++++++------- .../Testing/Python/SlicerBoundsTest.py | 4 +-- Base/Python/slicer/slicerqt.py | 3 +- Base/Python/slicer/util.py | 5 ++-- .../Testing/Python/MarkupsInViewsSelfTest.py | 2 +- .../Python/SegmentEditorDrawEffect.py | 3 +- .../SubjectHierarchyCorePluginsSelfTest.py | 2 +- Modules/Scripted/DICOM/DICOM.py | 4 +-- Modules/Scripted/DICOMLib/DICOMBrowser.py | 12 ++++---- Modules/Scripted/DICOMLib/DICOMUtils.py | 4 +-- .../DICOMPlugins/DICOMGeAbusPlugin.py | 2 +- .../ExtensionWizard/ExtensionWizard.py | 2 +- .../ExtensionWizardLib/EditableTreeWidget.py | 4 +-- Modules/Scripted/SampleData/SampleData.py | 4 +-- .../SegmentStatistics/SegmentStatistics.py | 16 ++++++---- .../LabelmapSegmentStatisticsPlugin.py | 8 ++--- .../SegmentStatisticsPluginBase.py | 9 ++++-- Modules/Scripted/WebServer/WebServer.py | 2 +- .../WebServerLib/SlicerRequestHandler.py | 6 ++-- .../SlicerWizard/ExtensionDescription.py | 13 ++++---- .../Scripts/SlicerWizard/ExtensionWizard.py | 2 +- .../Scripts/SlicerWizard/GithubHelper.py | 6 ++-- Utilities/Scripts/SlicerWizard/Utilities.py | 2 +- 24 files changed, 83 insertions(+), 74 deletions(-) diff --git a/.flake8 b/.flake8 index abd821adcba..abaf16fb25a 100644 --- a/.flake8 +++ b/.flake8 @@ -46,22 +46,10 @@ ignore = \ E402, \ # the backslash is redundant between bracket E502, \ - # multiple statements on one line (colon) - E701, \ - # statement ends with a semicolon - E703, \ - # comparison to True should be 'if cond is True:' or 'if cond:' - E712, \ - # test for membership should be 'not in' - E713, \ - # test for object identity should be 'is not' - E714, \ # do not use bare 'except' E722, \ # do not assign a lambda expression, use a def E731, \ - # ambiguous variable name 'l' - E741, \ # 'from module import *' used; unable to detect undefined names F403, \ # Name may be undefined, or defined from star import diff --git a/Applications/SlicerApp/Testing/Python/MeasureStartupTimes.py b/Applications/SlicerApp/Testing/Python/MeasureStartupTimes.py index 455db70e236..9b136add340 100755 --- a/Applications/SlicerApp/Testing/Python/MeasureStartupTimes.py +++ b/Applications/SlicerApp/Testing/Python/MeasureStartupTimes.py @@ -49,8 +49,10 @@ def collect_startup_times_normal(output_file, drop_cache=False, display_output=F (duration, result) = runSlicerAndExitWithTime(slicer_executable, test, drop_cache=drop_cache) (returnCode, stdout, stderr) = result if display_output: - if stdout: print("STDOUT [%s]\n" % stdout) - if stderr and returnCode == EXIT_SUCCESS: print("STDERR [%s]\n" % stderr) + if stdout: + print("STDOUT [%s]\n" % stdout) + if stderr and returnCode == EXIT_SUCCESS: + print("STDERR [%s]\n" % stderr) results[" ".join(test)] = duration with open(output_file, 'w') as file: file.write(json.dumps(results, indent=4)) @@ -84,8 +86,10 @@ def collect_startup_times_overall(output_file, drop_cache=False, display_output= (returnCode, stdout, stderr) = result if display_output: - if stdout: print("STDOUT [%s]\n" % stdout) - if stderr and returnCode == EXIT_SUCCESS: print("STDERR [%s]\n" % stderr) + if stdout: + print("STDOUT [%s]\n" % stdout) + if stderr and returnCode == EXIT_SUCCESS: + print("STDERR [%s]\n" % stderr) with open(output_file, 'w') as file: file.write(json.dumps(results, indent=4)) @@ -155,8 +159,10 @@ def collect_startup_times_including_one_module(output_file, module_list, drop_ca (duration, result) = runSlicerAndExitWithTime(slicer_executable, test, drop_cache=drop_cache) (returnCode, stdout, stderr) = result if display_output: - if stdout: print("STDOUT [%s]\n" % stdout) - if stderr and returnCode == EXIT_SUCCESS: print("STDERR [%s]\n" % stderr) + if stdout: + print("STDOUT [%s]\n" % stdout) + if stderr and returnCode == EXIT_SUCCESS: + print("STDERR [%s]\n" % stderr) if returnCode != EXIT_SUCCESS: # XXX Ignore module with dependencies duration = None @@ -180,8 +186,10 @@ def collect_startup_times_excluding_one_module(output_file, module_list, drop_ca (duration, result) = runSlicerAndExitWithTime(slicer_executable, ['--testing', '--modules-to-ignore', moduleName], drop_cache=drop_cache) (returnCode, stdout, stderr) = result if display_output: - if stdout: print("STDOUT [%s]\n" % stdout) - if stderr and returnCode == EXIT_SUCCESS: print("STDERR [%s]\n" % stderr) + if stdout: + print("STDOUT [%s]\n" % stdout) + if stderr and returnCode == EXIT_SUCCESS: + print("STDERR [%s]\n" % stderr) if returnCode != EXIT_SUCCESS: # XXX Ignore module with dependencies duration = None @@ -204,8 +212,10 @@ def collect_startup_times_modules_to_load(output_file, modules_to_load, module_l (duration, result) = runSlicerAndExitWithTime(slicer_executable, test, drop_cache=drop_cache) (returnCode, stdout, stderr) = result if display_output: - if stdout: print("STDOUT [%s]\n" % stdout) - if stderr and returnCode == EXIT_SUCCESS: print("STDERR [%s]\n" % stderr) + if stdout: + print("STDOUT [%s]\n" % stdout) + if stderr and returnCode == EXIT_SUCCESS: + print("STDERR [%s]\n" % stderr) results = {} results[" ".join(modulesToIgnore)] = duration diff --git a/Applications/SlicerApp/Testing/Python/SlicerBoundsTest.py b/Applications/SlicerApp/Testing/Python/SlicerBoundsTest.py index d93e11911cd..ce02708d4e7 100644 --- a/Applications/SlicerApp/Testing/Python/SlicerBoundsTest.py +++ b/Applications/SlicerApp/Testing/Python/SlicerBoundsTest.py @@ -55,8 +55,8 @@ def setUp(self): slicer.mrmlScene.Clear(0) def assertListAlmostEquals(self, list, expected): - for l, e in zip(list, expected): - self.assertAlmostEqual(l, e) + for list_item, expected_item in zip(list, expected): + self.assertAlmostEqual(list_item, expected_item) def runTest(self): """Run as few or as many tests as needed here. diff --git a/Base/Python/slicer/slicerqt.py b/Base/Python/slicer/slicerqt.py index 0ae5f88e568..08e74010015 100644 --- a/Base/Python/slicer/slicerqt.py +++ b/Base/Python/slicer/slicerqt.py @@ -12,7 +12,8 @@ # that way the following try/except could be avoided. try: import slicer.cli -except: pass +except: + pass # ----------------------------------------------------------------------------- diff --git a/Base/Python/slicer/util.py b/Base/Python/slicer/util.py index 51addc2d6d3..9297ce7c1d1 100644 --- a/Base/Python/slicer/util.py +++ b/Base/Python/slicer/util.py @@ -209,7 +209,8 @@ def lookupTopLevelWidget(objectName): from slicer import app for w in app.topLevelWidgets(): if hasattr(w, 'objectName'): - if w.objectName == objectName: return w + if w.objectName == objectName: + return w # not found raise RuntimeError("Failed to obtain reference to '%s'" % objectName) @@ -1259,7 +1260,7 @@ def reloadScriptedModule(moduleName): filePath = modulePath(moduleName) p = os.path.dirname(filePath) - if not p in sys.path: + if p not in sys.path: sys.path.insert(0, p) with open(filePath, encoding='utf8') as fp: diff --git a/Modules/Loadable/Markups/Testing/Python/MarkupsInViewsSelfTest.py b/Modules/Loadable/Markups/Testing/Python/MarkupsInViewsSelfTest.py index f8b07880540..6cadd4bb2ff 100644 --- a/Modules/Loadable/Markups/Testing/Python/MarkupsInViewsSelfTest.py +++ b/Modules/Loadable/Markups/Testing/Python/MarkupsInViewsSelfTest.py @@ -341,7 +341,7 @@ def test_MarkupsInViewsSelfTest1(self): logic = MarkupsInViewsSelfTestLogic() retval = logic.run() - if retval == True: + if retval is True: self.delayDisplay('Test passed!') else: self.delayDisplay('Test failed!') diff --git a/Modules/Loadable/Segmentations/EditorEffects/Python/SegmentEditorDrawEffect.py b/Modules/Loadable/Segmentations/EditorEffects/Python/SegmentEditorDrawEffect.py index 4e9e0e84fe8..e4f1e444e0c 100644 --- a/Modules/Loadable/Segmentations/EditorEffects/Python/SegmentEditorDrawEffect.py +++ b/Modules/Loadable/Segmentations/EditorEffects/Python/SegmentEditorDrawEffect.py @@ -235,7 +235,8 @@ def addPoint(self, ras): # Don't allow adding points on except on the active slice # (where first point was laid down) - if self.activeSliceOffset != currentSliceOffset: return + if self.activeSliceOffset != currentSliceOffset: + return # Keep track of node state (in case of pan/zoom) sliceNode = sliceLogic.GetSliceNode() diff --git a/Modules/Loadable/SubjectHierarchy/Testing/Python/SubjectHierarchyCorePluginsSelfTest.py b/Modules/Loadable/SubjectHierarchy/Testing/Python/SubjectHierarchyCorePluginsSelfTest.py index f190cf4d49e..68a3c1a27f2 100644 --- a/Modules/Loadable/SubjectHierarchy/Testing/Python/SubjectHierarchyCorePluginsSelfTest.py +++ b/Modules/Loadable/SubjectHierarchy/Testing/Python/SubjectHierarchyCorePluginsSelfTest.py @@ -108,7 +108,7 @@ def section_SetupPathsAndNames(self): self.cloneNodeNamePostfix = slicer.qSlicerSubjectHierarchyCloneNodePlugin().getCloneNodeNamePostfix() # Test printing of all context menu actions and their section numbers - pluginHandler = slicer.qSlicerSubjectHierarchyPluginHandler().instance(); + pluginHandler = slicer.qSlicerSubjectHierarchyPluginHandler().instance() print(pluginHandler.dumpContextMenuActions()) # ------------------------------------------------------------------------------ diff --git a/Modules/Scripted/DICOM/DICOM.py b/Modules/Scripted/DICOM/DICOM.py index a7cf76bdc02..db5b3e1fa05 100644 --- a/Modules/Scripted/DICOM/DICOM.py +++ b/Modules/Scripted/DICOM/DICOM.py @@ -125,10 +125,10 @@ def onURLReceived(self, urlString): for key, value in query.queryItems(qt.QUrl.FullyDecoded): queryMap[key] = qt.QUrl.fromPercentEncoding(value) - if not "dicomweb_endpoint" in queryMap: + if "dicomweb_endpoint" not in queryMap: logging.debug("DICOM module ignores URL without dicomweb_endpoint query parameter: " + urlString) return - if not "studyUID" in queryMap: + if "studyUID" not in queryMap: logging.debug("DICOM module ignores URL without studyUID query parameter: " + urlString) return diff --git a/Modules/Scripted/DICOMLib/DICOMBrowser.py b/Modules/Scripted/DICOMLib/DICOMBrowser.py index c91ae5f0baf..65d7cfc3f62 100644 --- a/Modules/Scripted/DICOMLib/DICOMBrowser.py +++ b/Modules/Scripted/DICOMLib/DICOMBrowser.py @@ -217,7 +217,7 @@ def promptForExtensions(self): displayedTypeDescriptions = [] for extension in extensionsToOffer: typeDescription = extension['typeDescription'] - if not typeDescription in displayedTypeDescriptions: + if typeDescription not in displayedTypeDescriptions: # only display each data type only once message += ' ' + typeDescription + '\n' displayedTypeDescriptions.append(typeDescription) @@ -225,7 +225,7 @@ def promptForExtensions(self): displayedExtensionNames = [] for extension in extensionsToOffer: extensionName = extension['name'] - if not extensionName in displayedExtensionNames: + if extensionName not in displayedExtensionNames: # only display each extension name only once message += ' ' + extensionName + '\n' displayedExtensionNames.append(extensionName) @@ -488,7 +488,7 @@ def loadCheckedLoadables(self): def showReferenceDialogAndProceed(self): referencesDialog = DICOMReferencesDialog(self, loadables=self.referencedLoadables) answer = referencesDialog.exec_() - if referencesDialog.rememberChoiceAndStopAskingCheckbox.checked == True: + if referencesDialog.rememberChoiceAndStopAskingCheckbox.checked is True: if answer == qt.QMessageBox.Yes: qt.QSettings().setValue('DICOM/automaticallyLoadReferences', qt.QMessageBox.Yes) if answer == qt.QMessageBox.No: @@ -497,7 +497,7 @@ def showReferenceDialogAndProceed(self): # each check box corresponds to a referenced loadable that was selected by examine; # if the user confirmed that reference should be loaded, add it to the self.loadablesByPlugin dictionary for plugin in self.referencedLoadables: - for loadable in [l for l in self.referencedLoadables[plugin] if l.selected]: + for loadable in [loadable_item for loadable_item in self.referencedLoadables[plugin] if loadable_item.selected]: if referencesDialog.checkboxes[loadable].checked: self.loadablesByPlugin[plugin].append(loadable) self.loadablesByPlugin[plugin] = list(set(self.loadablesByPlugin[plugin])) @@ -507,7 +507,7 @@ def showReferenceDialogAndProceed(self): def addReferencesAndProceed(self): for plugin in self.referencedLoadables: - for loadable in [l for l in self.referencedLoadables[plugin] if l.selected]: + for loadable in [loadable_item for loadable_item in self.referencedLoadables[plugin] if loadable_item.selected]: self.loadablesByPlugin[plugin].append(loadable) self.loadablesByPlugin[plugin] = list(set(self.loadablesByPlugin[plugin])) self.proceedWithReferencedLoadablesSelection() @@ -615,7 +615,7 @@ def _addLoadableCheckboxes(self): self.checkBoxGroupBox = qt.QGroupBox("References") self.checkBoxGroupBox.setLayout(qt.QFormLayout()) for plugin in self.loadables: - for loadable in [l for l in self.loadables[plugin] if l.selected]: + for loadable in [loadable_item for loadable_item in self.loadables[plugin] if loadable_item.selected]: checkBoxText = loadable.name + ' (' + plugin.loadType + ') ' cb = qt.QCheckBox(checkBoxText, self) cb.checked = True diff --git a/Modules/Scripted/DICOMLib/DICOMUtils.py b/Modules/Scripted/DICOMLib/DICOMUtils.py index a5917bae10e..75a0c012d0d 100644 --- a/Modules/Scripted/DICOMLib/DICOMUtils.py +++ b/Modules/Scripted/DICOMLib/DICOMUtils.py @@ -63,7 +63,7 @@ def loadPatientByUID(patientUID): raise OSError('DICOM module or database cannot be accessed') patientUIDstr = str(patientUID) - if not patientUIDstr in slicer.dicomDatabase.patients(): + if patientUIDstr not in slicer.dicomDatabase.patients(): raise OSError('No patient found with DICOM database UID %s' % patientUIDstr) # Select all series in selected patient @@ -864,7 +864,7 @@ def importFromDICOMWeb(dicomWebEndpoint, studyInstanceUID, seriesInstanceUID=Non seriesList = client.search_for_series(study_instance_uid=studyInstanceUID) seriesInstanceUIDs = [] - if not seriesInstanceUID is None: + if seriesInstanceUID is not None: seriesInstanceUIDs = [seriesInstanceUID] else: for series in seriesList: diff --git a/Modules/Scripted/DICOMPlugins/DICOMGeAbusPlugin.py b/Modules/Scripted/DICOMPlugins/DICOMGeAbusPlugin.py index 4f363842703..45fcd5ae411 100644 --- a/Modules/Scripted/DICOMPlugins/DICOMGeAbusPlugin.py +++ b/Modules/Scripted/DICOMPlugins/DICOMGeAbusPlugin.py @@ -156,7 +156,7 @@ def getMetadata(self, filePath): fieldInfo = fieldsInfo[fieldName] if not fieldInfo['required']: continue - if not fieldName in fieldValues: + if fieldName not in fieldValues: raise ValueError(f"Mandatory field {fieldName} was not found") return fieldValues diff --git a/Modules/Scripted/ExtensionWizard/ExtensionWizard.py b/Modules/Scripted/ExtensionWizard/ExtensionWizard.py index e2a3783f438..6ae4111e1bf 100644 --- a/Modules/Scripted/ExtensionWizard/ExtensionWizard.py +++ b/Modules/Scripted/ExtensionWizard/ExtensionWizard.py @@ -357,7 +357,7 @@ def loadModules(self, path, depth=1): for module in modulesToLoad: rawPath = os.path.dirname(module.path) path = qt.QDir(rawPath) - if not path in searchPaths: + if path not in searchPaths: searchPaths.append(path) rawSearchPaths.append(rawPath) modified = True diff --git a/Modules/Scripted/ExtensionWizard/ExtensionWizardLib/EditableTreeWidget.py b/Modules/Scripted/ExtensionWizard/ExtensionWizardLib/EditableTreeWidget.py index aa0a8615af6..b555a26fe67 100644 --- a/Modules/Scripted/ExtensionWizard/ExtensionWizardLib/EditableTreeWidget.py +++ b/Modules/Scripted/ExtensionWizard/ExtensionWizardLib/EditableTreeWidget.py @@ -113,8 +113,8 @@ def updateActions(self): last = self.topLevelItemCount - 2 - self._shiftUpAction.enabled = len(rows) and not 0 in rows - self._shiftDownAction.enabled = len(rows) and not last in rows + self._shiftUpAction.enabled = len(rows) and 0 not in rows + self._shiftDownAction.enabled = len(rows) and last not in rows self._deleteAction.enabled = True if len(rows) else False # --------------------------------------------------------------------------- diff --git a/Modules/Scripted/SampleData/SampleData.py b/Modules/Scripted/SampleData/SampleData.py index 53b63eab395..dd108364b7d 100644 --- a/Modules/Scripted/SampleData/SampleData.py +++ b/Modules/Scripted/SampleData/SampleData.py @@ -672,7 +672,7 @@ def downloadFromSource(self, source, maximumAttemptsCount=3): resultFilePaths.append(filePath) if loadFileType == 'ZipFile': - if loadFile == False: + if loadFile is False: resultNodes.append(filePath) break outputDir = slicer.mrmlScene.GetCacheManager().GetRemoteCacheDirectory() + "/" + os.path.splitext(os.path.basename(filePath))[0] @@ -690,7 +690,7 @@ def downloadFromSource(self, source, maximumAttemptsCount=3): resultNodes.append(filePath) break elif nodeName: - if loadFile == False: + if loadFile is False: resultNodes.append(filePath) break loadedNode = self.loadNode(filePath, nodeName, loadFileType, source.loadFileProperties.copy()) diff --git a/Modules/Scripted/SegmentStatistics/SegmentStatistics.py b/Modules/Scripted/SegmentStatistics/SegmentStatistics.py index b120ca1021d..64772ad1d58 100644 --- a/Modules/Scripted/SegmentStatistics/SegmentStatistics.py +++ b/Modules/Scripted/SegmentStatistics/SegmentStatistics.py @@ -369,7 +369,7 @@ def registerPlugin(plugin): if key.count(".") > 0: logging.warning("Plugin keys should not contain extra '.' as it might mix pluginname.measurementkey in " "the parameter node") - if not plugin.__class__ in SegmentStatisticsLogic.registeredPlugins: + if plugin.__class__ not in SegmentStatisticsLogic.registeredPlugins: SegmentStatisticsLogic.registeredPlugins.append(plugin.__class__) else: logging.warning("SegmentStatisticsLogic.registerPlugin will not register plugin because \ @@ -454,7 +454,7 @@ def computeStatistics(self): segmentID = visibleSegmentIds.GetValue(segmentIndex) self.updateStatisticsForSegment(segmentID) finally: - if not transformedSegmentationNode is None: + if transformedSegmentationNode is not None: # We made a copy and hardened the segmentation transform self.getParameterNode().SetParameter("Segmentation", segmentationNode.GetID()) slicer.mrmlScene.RemoveNode(transformedSegmentationNode) @@ -549,8 +549,10 @@ def getHeaderNames(self, nonEmptyKeysOnly=True): if dicomBasedName and 'DICOM.UnitsCode' in info and info['DICOM.UnitsCode']: entry.SetFromString(info['DICOM.UnitsCode']) units = entry.GetCodeValue() - if len(units) > 0 and units[0] == '[' and units[-1] == ']': units = units[1:-1] - if len(units) > 0: name += ' [' + units + ']' + if len(units) > 0 and units[0] == '[' and units[-1] == ']': + units = units[1:-1] + if len(units) > 0: + name += ' [' + units + ']' elif 'units' in info and info['units'] and len(info['units']) > 0: units = info['units'] name += ' [' + units + ']' @@ -805,14 +807,16 @@ def test_SegmentStatisticsPlugins(self): segStatLogic.exportToTable(resultsTableNode) segStatLogic.showTable(resultsTableNode) self.assertEqual(segStatLogic.getStatistics()["Test_2", "LabelmapSegmentStatisticsPlugin.voxel_count"], 9807) - with self.assertRaises(KeyError): segStatLogic.getStatistics()["Test_4", "ScalarVolumeSegmentStatisticsPlugin.voxel count"] + with self.assertRaises(KeyError): + segStatLogic.getStatistics()["Test_4", "ScalarVolumeSegmentStatisticsPlugin.voxel count"] # assert there are no result for this segment segStatLogic.updateStatisticsForSegment('Test_4') segStatLogic.exportToTable(resultsTableNode) segStatLogic.showTable(resultsTableNode) self.assertEqual(segStatLogic.getStatistics()["Test_2", "LabelmapSegmentStatisticsPlugin.voxel_count"], 9807) self.assertEqual(segStatLogic.getStatistics()["Test_4", "LabelmapSegmentStatisticsPlugin.voxel_count"], 380) - with self.assertRaises(KeyError): segStatLogic.getStatistics()["Test_5", "ScalarVolumeSegmentStatisticsPlugin.voxel count"] + with self.assertRaises(KeyError): + segStatLogic.getStatistics()["Test_5", "ScalarVolumeSegmentStatisticsPlugin.voxel count"] # assert there are no result for this segment # calculate measurements for all segments diff --git a/Modules/Scripted/SegmentStatistics/SegmentStatisticsPlugins/LabelmapSegmentStatisticsPlugin.py b/Modules/Scripted/SegmentStatistics/SegmentStatisticsPlugins/LabelmapSegmentStatisticsPlugin.py index 3ec4239adfc..c38f80f49ef 100644 --- a/Modules/Scripted/SegmentStatistics/SegmentStatisticsPlugins/LabelmapSegmentStatisticsPlugin.py +++ b/Modules/Scripted/SegmentStatistics/SegmentStatisticsPlugins/LabelmapSegmentStatisticsPlugin.py @@ -122,14 +122,14 @@ def computeStatistics(self, segmentID): temp = statFilterOptions statFilterOptions = [] for option in temp: - if not option in self.obbKeys: + if option not in self.obbKeys: statFilterOptions.append(option) statFilterOptions.append("oriented_bounding_box") temp = requestedOptions requestedOptions = [] for option in temp: - if not option in self.obbKeys: + if option not in self.obbKeys: requestedOptions.append(option) requestedOptions.append("oriented_bounding_box") @@ -142,14 +142,14 @@ def computeStatistics(self, segmentID): temp = statFilterOptions statFilterOptions = [] for option in temp: - if not option in self.principalAxisKeys: + if option not in self.principalAxisKeys: statFilterOptions.append(option) statFilterOptions.append("principal_axes") temp = requestedOptions requestedOptions = [] for option in temp: - if not option in self.principalAxisKeys: + if option not in self.principalAxisKeys: requestedOptions.append(option) requestedOptions.append("principal_axes") requestedOptions.append("centroid_ras") diff --git a/Modules/Scripted/SegmentStatistics/SegmentStatisticsPlugins/SegmentStatisticsPluginBase.py b/Modules/Scripted/SegmentStatistics/SegmentStatisticsPlugins/SegmentStatisticsPluginBase.py index 2b7528c4462..15b9f7c4e52 100644 --- a/Modules/Scripted/SegmentStatistics/SegmentStatisticsPlugins/SegmentStatisticsPluginBase.py +++ b/Modules/Scripted/SegmentStatistics/SegmentStatisticsPlugins/SegmentStatisticsPluginBase.py @@ -149,9 +149,12 @@ def createDefaultOptionsWidget(self): info = self.getMeasurementInfo(key) if info and ("name" in info or "description" in info): label = info["name"] if "name" in info else info["description"] - if "name" in info: tooltip += "\nname: " + str(info["name"]) - if "description" in info: tooltip += "\ndescription: " + str(info["description"]) - if "units" in info: tooltip += "\nunits: " + (str(info["units"]) if info["units"] else "n/a") + if "name" in info: + tooltip += "\nname: " + str(info["name"]) + if "description" in info: + tooltip += "\ndescription: " + str(info["description"]) + if "units" in info: + tooltip += "\nunits: " + (str(info["units"]) if info["units"] else "n/a") checkbox = qt.QCheckBox(label, self.optionsWidget) checkbox.checked = key in requestedKeys checkbox.setToolTip(tooltip) diff --git a/Modules/Scripted/WebServer/WebServer.py b/Modules/Scripted/WebServer/WebServer.py index 597d975418d..cbf64b89fd9 100644 --- a/Modules/Scripted/WebServer/WebServer.py +++ b/Modules/Scripted/WebServer/WebServer.py @@ -392,7 +392,7 @@ def onReadable(self, fileno): # TODO: methods = ["GET", "POST", "PUT", "DELETE"] methods = [b"GET", b"POST", b"PUT"] - if not method in methods: + if method not in methods: self.logMessage("Warning, we only handle %s" % methods) return diff --git a/Modules/Scripted/WebServer/WebServerLib/SlicerRequestHandler.py b/Modules/Scripted/WebServer/WebServerLib/SlicerRequestHandler.py index 2dda9632c0e..9e5f9f447be 100644 --- a/Modules/Scripted/WebServer/WebServerLib/SlicerRequestHandler.py +++ b/Modules/Scripted/WebServer/WebServerLib/SlicerRequestHandler.py @@ -242,7 +242,7 @@ def volumeSelection(self, request): except KeyError: cmd = 'next' options = ['next', 'previous'] - if not cmd in options: + if cmd not in options: cmd = 'next' applicationLogic = slicer.app.applicationLogic() @@ -605,7 +605,7 @@ def fiducial(self, request, requestBody): s = 0 fiducialNode = slicer.util.getNode(fiducialID) - fiducialNode.SetNthFiducialPosition(index, float(r), float(a), float(s)); + fiducialNode.SetNthFiducialPosition(index, float(r), float(a), float(s)) return "{'result': 'ok'}", b'application/json' def accessDICOMwebStudy(self, request, requestBody): @@ -733,7 +733,7 @@ def slice(self, request): except KeyError: view = 'red' options = ['red', 'yellow', 'green'] - if not view in options: + if view not in options: view = 'red' layoutManager = slicer.app.layoutManager() sliceLogic = layoutManager.sliceWidget(view.capitalize()).sliceLogic() diff --git a/Utilities/Scripts/SlicerWizard/ExtensionDescription.py b/Utilities/Scripts/SlicerWizard/ExtensionDescription.py index 44822a46eff..0f5a711b2d4 100644 --- a/Utilities/Scripts/SlicerWizard/ExtensionDescription.py +++ b/Utilities/Scripts/SlicerWizard/ExtensionDescription.py @@ -173,9 +173,9 @@ def _remotePublicUrl(remote): @staticmethod def _gitSvnInfo(repo, remote): result = {} - for l in repo.git.svn('info', R=remote).split("\n"): - if len(l): - key, value = l.split(":", 1) + for line in repo.git.svn('info', R=remote).split("\n"): + if len(line): + key, value = line.split(":", 1) result[key] = value.strip() return result @@ -208,8 +208,8 @@ def clear(self, attr=None): # --------------------------------------------------------------------------- def _read(self, fp): - for l in fp: - m = self._reParam.match(l) + for line in fp: + m = self._reParam.match(line) if m is not None: setattr(self, m.group(1), m.group(2).strip()) @@ -247,7 +247,8 @@ def _findOccurences(a_str, sub): start = 0 while True: start = a_str.find(sub, start) - if start == -1: return + if start == -1: + return yield start start += len(sub) diff --git a/Utilities/Scripts/SlicerWizard/ExtensionWizard.py b/Utilities/Scripts/SlicerWizard/ExtensionWizard.py index 37f773ea666..e5d0507024d 100644 --- a/Utilities/Scripts/SlicerWizard/ExtensionWizard.py +++ b/Utilities/Scripts/SlicerWizard/ExtensionWizard.py @@ -486,7 +486,7 @@ def contribute(self, args): # Update the index repository and get the base branch logging.info("updating local index clone") xiRepo.git.fetch(xiUpstream) - if not args.target in xiUpstream.refs: + if args.target not in xiUpstream.refs: die("target branch '%s' does not exist" % args.target) xiBase = xiUpstream.refs[args.target] diff --git a/Utilities/Scripts/SlicerWizard/GithubHelper.py b/Utilities/Scripts/SlicerWizard/GithubHelper.py index b089e35b5b9..562eaa5dfac 100644 --- a/Utilities/Scripts/SlicerWizard/GithubHelper.py +++ b/Utilities/Scripts/SlicerWizard/GithubHelper.py @@ -28,9 +28,9 @@ def __init__(self, text=None, **kwargs): # Set attributes from input text (i.e. 'git credential fill' output) if text is not None: - for l in text.split("\n"): - if "=" in l: - t = l.split("=", 1) + for line in text.split("\n"): + if "=" in line: + t = line.split("=", 1) self._keys.add(t[0]) setattr(self, t[0], t[1]) diff --git a/Utilities/Scripts/SlicerWizard/Utilities.py b/Utilities/Scripts/SlicerWizard/Utilities.py index e479cc1a7e3..c88a70ad428 100644 --- a/Utilities/Scripts/SlicerWizard/Utilities.py +++ b/Utilities/Scripts/SlicerWizard/Utilities.py @@ -69,7 +69,7 @@ def __init__(self): # --------------------------------------------------------------------------- def format(self, record): lines = super().format(record).split("\n") - return "\n".join([textwrap.fill(l, self._width) for l in lines]) + return "\n".join([textwrap.fill(line, self._width) for line in lines]) # =============================================================================