Skip to content

Commit 92e8db0

Browse files
authored
Merge pull request #23 from jamesobutler/pyupgrade-fixes
STYLE: Upgrade python syntax to 3.6 and newer
2 parents fb84920 + 4e8a847 commit 92e8db0

3 files changed

Lines changed: 33 additions & 37 deletions

File tree

SimpleFilters/SimpleFilters.py

Lines changed: 32 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from __future__ import print_function
21
from functools import reduce
32
import os,sys
43
import unittest
@@ -26,7 +25,7 @@
2625
# SimpleFilters
2726
#
2827

29-
class SimpleFilters(object):
28+
class SimpleFilters:
3029

3130
# Use class-level scoped variable for module consants
3231
if not __file__.endswith("SimpleFilters.py"):
@@ -56,7 +55,7 @@ def __init__(self, parent):
5655
largest possible region), and be the same pixel type.
5756
<br /><br />
5857
59-
For general information about the module see the <a href=\"{0}/Documentation/Nightly/Modules/SimpleFilters\">online documentation</a>.
58+
For general information about the module see the <a href=\"{}/Documentation/Nightly/Modules/SimpleFilters\">online documentation</a>.
6059
<br /><br />
6160
6261
For detailed information about a specific filter please consult the <a href=\"http://www.itk.org/Doxygen/html/\">Insight Toolkit Doxygen</a>.
@@ -75,7 +74,7 @@ def __init__(self, parent):
7574
# qSimpleFiltersWidget
7675
#
7776

78-
class SimpleFiltersWidget(object):
77+
class SimpleFiltersWidget:
7978
def __init__(self, parent = None):
8079

8180
# To avoid the overhead of importing SimpleITK during application
@@ -103,17 +102,17 @@ def __init__(self, parent = None):
103102

104103
for fname in jsonFiles:
105104
try:
106-
with open(fname, "r") as fp:
105+
with open(fname) as fp:
107106
j = json.load(fp,object_pairs_hook=OrderedDict)
108107
if j["name"] in dir(sitk):
109108
self.jsonFilters.append(j)
110109
else:
111110
if j["itk_module"] in sitk.Version().ITKModulesEnabled():
112111
import sys
113-
sys.stderr.write("Unknown SimpleITK class \"{0}\".\n".format(j["name"]))
112+
sys.stderr.write("Unknown SimpleITK class \"{}\".\n".format(j["name"]))
114113
except Exception as e:
115114
import sys
116-
sys.stderr.write("Error while reading \"{0}\". Exception: {1}\n".format(fname, e))
115+
sys.stderr.write(f"Error while reading \"{fname}\". Exception: {e}\n")
117116

118117

119118
self.filterParameters = None
@@ -225,15 +224,15 @@ def printPythonCommand(self):
225224
printStr = []
226225
currentFilter = self.filterParameters.filter
227226
varName = currentFilter.__class__.__name__
228-
printStr.append('myFilter = {0}()'.format(varName))
227+
printStr.append(f'myFilter = {varName}()')
229228
for key in dir(currentFilter):
230229
if key == 'GetName' or key.startswith('GetGlobal'):
231230
pass
232231
elif key[:3] == 'Get':
233232
setAttr = key.replace("Get", "Set", 1)
234233
if hasattr(currentFilter, setAttr):
235-
value = eval("currentFilter.{0}()".format( key))
236-
printStr.append('myFilter.{0}({1})'.format(setAttr, value))
234+
value = eval(f"currentFilter.{key}()")
235+
printStr.append(f'myFilter.{setAttr}({value})')
237236

238237
print("\n".join(printStr))
239238

@@ -310,15 +309,15 @@ def onApplyButton(self):
310309

311310

312311
qt.QMessageBox.critical(slicer.util.mainWindow(),
313-
"Exception before execution of {0}".format(self.filterParameters.filter.GetName()),
312+
f"Exception before execution of {self.filterParameters.filter.GetName()}",
314313
msg)
315314

316315

317316

318317
def onCancelButton(self):
319318
self.currentStatusLabel.text = "Aborting"
320319
if self.logic:
321-
self.logic.abort = True;
320+
self.logic.abort = True
322321

323322

324323
def onLogicEventStart(self):
@@ -331,7 +330,7 @@ def onLogicEventStart(self):
331330

332331
def onLogicEventEnd(self):
333332
elapsedTimeSec = time.time() - self.filterStartTime
334-
self.currentStatusLabel.text = "Completed ({0:3.1f}s)".format(elapsedTimeSec)
333+
self.currentStatusLabel.text = f"Completed ({elapsedTimeSec:3.1f}s)"
335334
self.progress.setValue(1000)
336335

337336

@@ -341,7 +340,7 @@ def onLogicEventAbort(self):
341340

342341

343342
def onLogicEventProgress(self, progress):
344-
self.currentStatusLabel.text = "Running ({0:3.1f}%)".format(progress*100.0)
343+
self.currentStatusLabel.text = "Running ({:3.1f}%)".format(progress*100.0)
345344
self.progress.setValue(progress*1000)
346345

347346

@@ -354,7 +353,7 @@ def onLogicEventIteration(self, nIter):
354353
# SimpleFiltersLogic
355354
#
356355

357-
class SimpleFiltersLogic(object):
356+
class SimpleFiltersLogic:
358357
"""This class should implement all the actual
359358
computation done by your module. The interface
360359
should be such that other python code can import
@@ -402,7 +401,6 @@ def cmdIterationEvent(self, sitkFilter, nIter):
402401
print("cmIterationEvent")
403402
widget = slicer.modules.SimpleFiltersWidget
404403
self.main_queue.put(lambda: widget.onLogicEventIteration(nIter))
405-
++nIter;
406404
self.cmdCheckAbort(sitkFilter)
407405
self.yieldPythonGIL()
408406

@@ -447,7 +445,7 @@ def thread_doit(self,sitkFilter,*inputImages):
447445

448446
self.yieldPythonGIL()
449447
self.main_queue.put(lambda :qt.QMessageBox.critical(slicer.util.mainWindow(),
450-
"Exception during execution of {0}".format(sitkFilter.GetName()),
448+
f"Exception during execution of {sitkFilter.GetName()}",
451449
msg))
452450
finally:
453451
# this filter is persistent, remove commands
@@ -483,7 +481,7 @@ def main_queue_process(self):
483481

484482
except Exception as e:
485483
import sys
486-
sys.stderr.write("FilterLogic error in main_queue: \"{0}\"".format(e))
484+
sys.stderr.write(f"FilterLogic error in main_queue: \"{e}\"")
487485

488486
# if there was an error try to resume
489487
if not self.main_queue.empty() or self.main_queue_running:
@@ -544,7 +542,7 @@ def run(self, filter, outputMRMLNode, outputLabelMap, *inputs):
544542
# Class to manage parameters
545543
#
546544

547-
class FilterParameters(object):
545+
class FilterParameters:
548546
""" This class is for managing the widgets for the parameters for a filter
549547
"""
550548

@@ -579,7 +577,7 @@ def create(self, json):
579577
parametersFormLayout = self.parent.layout()
580578

581579
# You can't use exec in a function that has a subfunction, unless you specify a context.
582-
exec('self.filter = sitk.{0}()'.format(json["name"]), globals(), locals())
580+
exec('self.filter = sitk.{}()'.format(json["name"]), globals(), locals())
583581

584582
self.prerun_callbacks = []
585583
self.inputs = []
@@ -598,10 +596,10 @@ def create(self, json):
598596

599597
name = "Input Volume: "
600598
if "name" in input:
601-
name = "Input {0}: ".format(input["name"])
599+
name = "Input {}: ".format(input["name"])
602600
name = name.replace("Image", "Volume")
603601

604-
print("adding {1}: {0}".format(name,n))
602+
print(f"adding {n}: {name}")
605603
inputSelectorLabel = qt.QLabel(name)
606604
self.widgets.append(inputSelectorLabel)
607605

@@ -614,7 +612,7 @@ def create(self, json):
614612

615613
if "number_of_inputs" in json and json["number_of_inputs"] != 0:
616614
import sys
617-
sys.stderr.write("Expected \"number_of_inputs\" to be 0 not {0}!".format(json["number_of_inputs"]))
615+
sys.stderr.write("Expected \"number_of_inputs\" to be 0 not {}!".format(json["number_of_inputs"]))
618616

619617
else:
620618

@@ -673,7 +671,7 @@ def create(self, json):
673671
self.widgetConnections.append((fiducialSelector, "nodeActivated(vtkMRMLNode*)"))
674672
self.prerun_callbacks.append(lambda w=fiducialSelector,name=name:self.onFiducialListNode(name,w.currentNode()))
675673

676-
fiducialSelectorLabel = qt.QLabel("{0}: ".format(name))
674+
fiducialSelectorLabel = qt.QLabel(f"{name}: ")
677675
self.widgets.append(fiducialSelectorLabel)
678676

679677
#todo set tool tip
@@ -712,7 +710,7 @@ def create(self, json):
712710

713711
w1 = fiducialSelector
714712

715-
fiducialSelectorLabel = qt.QLabel("{0}: ".format(member["name"]))
713+
fiducialSelectorLabel = qt.QLabel("{}: ".format(member["name"]))
716714
self.widgets.append(fiducialSelectorLabel)
717715

718716
icon = qt.QIcon(SimpleFilters.ICON_DIR+"Fiducials.png")
@@ -826,7 +824,7 @@ def create(self, json):
826824
w = self.createLargeIntWidget(member["name"])
827825
else:
828826
import sys
829-
sys.stderr.write("Unknown member \"{0}\" of type \"{1}\"\n".format(member["name"],member["type"]))
827+
sys.stderr.write("Unknown member \"{}\" of type \"{}\"\n".format(member["name"],member["type"]))
830828

831829
if w:
832830
self.addWidgetWithToolTipAndLabel(w,member)
@@ -997,7 +995,7 @@ def createBoolWidget(self,name):
997995

998996
def _getParameterValue(self, parameterName):
999997
ldict = locals().copy()
1000-
exec('default = self.filter.Get{0}()'.format(parameterName), globals(), ldict)
998+
exec(f'default = self.filter.Get{parameterName}()', globals(), ldict)
1001999
return ldict['default']
10021000

10031001
def createDoubleWidget(self,name):
@@ -1080,7 +1078,7 @@ def onFiducialNode(self, name, mrmlWidget, isPoint):
10801078
imgNodeName = self.inputs[0].GetName()
10811079
img = sitk.ReadImage(sitkUtils.GetSlicerITKReadWriteAddress(imgNodeName) )
10821080
coord = img.TransformPhysicalPointToIndex(coord)
1083-
exec('self.filter.Set{0}(coord)'.format(name))
1081+
exec(f'self.filter.Set{name}(coord)')
10841082

10851083
def onFiducialListNode(self, name, mrmlNode):
10861084
annotationHierarchyNode = mrmlNode
@@ -1120,26 +1118,26 @@ def onFiducialListNode(self, name, mrmlNode):
11201118

11211119
idx_coords = [img.TransformPhysicalPointToIndex(pt) for pt in coords]
11221120

1123-
exec('self.filter.Set{0}(idx_coords)'.format(name))
1121+
exec(f'self.filter.Set{name}(idx_coords)')
11241122

11251123
def onScalarChanged(self, name, val):
1126-
exec('self.filter.Set{0}(val)'.format(name))
1124+
exec(f'self.filter.Set{name}(val)')
11271125

11281126
def onEnumChanged(self, name, selectorIndex, selector):
11291127
data=selector.itemData(selectorIndex)
1130-
exec('self.filter.Set{0}({1})'.format(name,data))
1128+
exec(f'self.filter.Set{name}({data})')
11311129

11321130
def onBoolVectorChanged(self, name, widget, val):
11331131
coords = [bool(float(x)) for x in widget.coordinates.split(',')]
1134-
exec('self.filter.Set{0}(coords)'.format(name))
1132+
exec(f'self.filter.Set{name}(coords)')
11351133

11361134
def onIntVectorChanged(self, name, widget, val):
11371135
coords = [int(float(x)) for x in widget.coordinates.split(',')]
1138-
exec('self.filter.Set{0}(coords)'.format(name))
1136+
exec(f'self.filter.Set{name}(coords)')
11391137

11401138
def onFloatVectorChanged(self, name, widget, val):
11411139
coords = [float(x) for x in widget.coordinates.split(',')]
1142-
exec('self.filter.Set{0}(coords)'.format(name))
1140+
exec(f'self.filter.Set{name}(coords)')
11431141

11441142

11451143
def prerun(self):

SimpleFilters/Testing/Python/SimpleFiltersModuleTest.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from __future__ import print_function
21
import unittest
32
import qt
43
import slicer
@@ -46,6 +45,6 @@ def test_SimpleFilters1(self):
4645
for filterIdx in range(testWidget.filterSelector.count):
4746
someJSON=slicer.modules.SimpleFiltersWidget.jsonFilters[filterIdx]
4847
testWidget.filterSelector.setCurrentIndex(filterIdx)
49-
self.delayDisplay("Testing filter \"{0}\" ({1} of {2}).".format(someJSON["name"], filterIdx, testWidget.filterSelector.count),msec=100 )
48+
self.delayDisplay("Testing filter \"{}\" ({} of {}).".format(someJSON["name"], filterIdx, testWidget.filterSelector.count),msec=100 )
5049

5150
return True

Utilities/JSONGenerateWikiDocs.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
# Usage: Utilities/JSONGenerateWikiDocs.py SimpleFilters/Resources/json/*.json
1010
#
1111

12-
from __future__ import print_function
1312
import json
1413
import sys
1514
try:

0 commit comments

Comments
 (0)