Skip to content

Commit

Permalink
STYLE: Upgrade python syntax to 3.9 and newer
Browse files Browse the repository at this point in the history
Changes were applied automatically by running:
pre_commit run --all-files
  • Loading branch information
jamesobutler committed Sep 29, 2022
1 parent 868d5fd commit 9f7b811
Show file tree
Hide file tree
Showing 10 changed files with 24 additions and 25 deletions.
6 changes: 3 additions & 3 deletions Applications/SlicerApp/Testing/Python/CLISerializationTest.py
Expand Up @@ -70,9 +70,9 @@ def deserializeCLI(self, cli_name, json_file_path, parameters=[]):
temp_dir = os.path.expanduser(getattr(args, "/path/to/temp_dir"))

# Create input/output
serializeSeedsOutFile = '%s/%s.acsv' % (temp_dir, 'SeedsSerialized')
deserializeSeedsOutFile = '%s/%s.acsv' % (temp_dir, 'SeedsDeSerialized')
json_file = '%s/%s.json' % (temp_dir, 'ExecutionModelTourSerialized')
serializeSeedsOutFile = f'{temp_dir}/SeedsSerialized.acsv'
deserializeSeedsOutFile = f'{temp_dir}/SeedsDeSerialized.acsv'
json_file = f'{temp_dir}/ExecutionModelTourSerialized.json'

# Copy .mrml file to prevent modification of source tree
mrml_source_path = os.path.join(data_dir, 'ExecutionModelTourTest.mrml')
Expand Down
2 changes: 1 addition & 1 deletion Base/Python/slicer/ScriptedLoadableModule.py
Expand Up @@ -299,7 +299,7 @@ class ScriptedLoadableModuleTest(unittest.TestCase):
"""

def __init__(self, *args, **kwargs):
super(ScriptedLoadableModuleTest, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

# See https://github.com/Slicer/Slicer/pull/6243#issuecomment-1061800718 for more information.
# Do not pass *args, **kwargs since there is no base class after `unittest.TestCase`. This is only relevant to
Expand Down
4 changes: 2 additions & 2 deletions Base/Python/slicer/util.py
Expand Up @@ -2707,7 +2707,7 @@ def _messageDisplay(logLevel, text, testingReturnValue, mainWindowNeeded=False,
if not windowTitle:
windowTitle = slicer.app.applicationName + " " + logLevelString
if slicer.app.testingEnabled():
logging.info("Testing mode is enabled: Returning %s and skipping message box [%s]." % (testingReturnValue, windowTitle))
logging.info(f"Testing mode is enabled: Returning {testingReturnValue} and skipping message box [{windowTitle}].")
return testingReturnValue
if mainWindowNeeded and mainWindow() is None:
return
Expand All @@ -2730,7 +2730,7 @@ def messageBox(text, parent=None, **kwargs):
import logging, qt, slicer
if slicer.app.testingEnabled():
testingReturnValue = qt.QMessageBox.Ok
logging.info("Testing mode is enabled: Returning %s (qt.QMessageBox.Ok) and displaying an auto-closing message box [%s]." % (testingReturnValue, text))
logging.info(f"Testing mode is enabled: Returning {testingReturnValue} (qt.QMessageBox.Ok) and displaying an auto-closing message box [{text}].")
slicer.util.delayDisplay(text, autoCloseMsec=3000, parent=parent, **kwargs)
return testingReturnValue

Expand Down
@@ -1,4 +1,3 @@

import vtk

import slicer
Expand Down
2 changes: 1 addition & 1 deletion Modules/Scripted/DataProbe/DataProbe.py
Expand Up @@ -169,7 +169,7 @@ def getPixelString(self, volumeNode, ijk):
value = self.calculateTensorScalars(tensor, operation=operation)
if value is not None:
valueString = ("%f" % value).rstrip('0').rstrip('.')
return "%s %s" % (scalarVolumeDisplayNode.GetScalarInvariantAsString(), valueString)
return f"{scalarVolumeDisplayNode.GetScalarInvariantAsString()} {valueString}"
else:
return scalarVolumeDisplayNode.GetScalarInvariantAsString()

Expand Down
4 changes: 2 additions & 2 deletions Modules/Scripted/ImportItkSnapLabel/ImportItkSnapLabel.py
Expand Up @@ -26,7 +26,7 @@ def __init__(self, parent):
# (identified by its special name <moduleName>FileReader)
#

class ImportItkSnapLabelFileReader(object):
class ImportItkSnapLabelFileReader:

def __init__(self, parent):
self.parent = parent
Expand Down Expand Up @@ -115,7 +115,7 @@ def parseLabelFile(filename):
colors = []

lineIndex = 0
with open(filename, "r") as fileobj:
with open(filename) as fileobj:
for line in fileobj:
lineIndex += 1
commentLine = commentLineRegex.search(line)
Expand Down
14 changes: 7 additions & 7 deletions Modules/Scripted/WebServer/WebServer.py
Expand Up @@ -287,10 +287,10 @@ def __init__(self, server_address=("", 2016), requestHandlers=None, docroot='.',
self.connections = {}
self.requestCommunicators = {}

class DummyRequestHandler(object):
class DummyRequestHandler():
pass

class SlicerRequestCommunicator(object):
class SlicerRequestCommunicator():
"""
Encapsulate elements for handling event driven read of request.
An instance is created for each client connection to our web server.
Expand Down Expand Up @@ -361,7 +361,7 @@ def onReadable(self, fileno):
self.logMessage('Found end of header with no content, so body is empty')
requestHeader = self.requestSoFar[:-2]
requestComplete = True
except socket.error as e:
except OSError as e:
print('Socket error: ', e)
print('So far:\n', self.requestSoFar)
requestComplete = True
Expand Down Expand Up @@ -458,7 +458,7 @@ def onWritable(self, fileno):
self.response = self.response[sent:]
self.sentSoFar += sent
self.logMessage('sent: %d (%d of %d, %f%%)' % (sent, self.sentSoFar, self.toSend, 100. * self.sentSoFar / self.toSend))
except socket.error as e:
except OSError as e:
self.logMessage('Socket error while sending: %s' % e)
sendError = True

Expand All @@ -476,8 +476,8 @@ def onServerSocketNotify(self, fileno):
fileno = connectionSocket.fileno()
self.requestCommunicators[fileno] = self.SlicerRequestCommunicator(connectionSocket, self.requestHandlers, self.docroot, self.logMessage)
self.logMessage('Connected on %s fileno %d' % (connectionSocket, connectionSocket.fileno()))
except socket.error as e:
self.logMessage('Socket Error', socket.error, e)
except OSError as e:
self.logMessage('Socket Error', OSError, e)

def start(self):
"""start the server
Expand Down Expand Up @@ -520,7 +520,7 @@ def findFreePort(self, port=2016):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("", port))
except socket.error as e:
except OSError as e:
portFree = False
port += 1
finally:
Expand Down
Expand Up @@ -5,7 +5,7 @@
import slicer


class DICOMRequestHandler(object):
class DICOMRequestHandler():
"""
Implements the mapping between DICOMweb endpoints
and ctkDICOMDatabase api calls.
Expand Down Expand Up @@ -101,13 +101,13 @@ def handleStudies(self, parsedURL, requestBody):
firstInstance = instances[0]
dataset = pydicom.dcmread(slicer.dicomDatabase.fileForInstance(firstInstance), stop_before_pixels=True)
studyDataset = pydicom.dataset.Dataset()
studyDataset.SpecificCharacterSet = [u'ISO_IR 100']
studyDataset.SpecificCharacterSet = ['ISO_IR 100']
studyDataset.StudyDate = dataset.StudyDate
studyDataset.StudyTime = dataset.StudyTime
studyDataset.StudyDescription = dataset.StudyDescription if hasattr(studyDataset, 'StudyDescription') else None
studyDataset.StudyInstanceUID = dataset.StudyInstanceUID
studyDataset.AccessionNumber = dataset.AccessionNumber
studyDataset.InstanceAvailability = u'ONLINE'
studyDataset.InstanceAvailability = 'ONLINE'
studyDataset.ModalitiesInStudy = list(modalitiesInStudy)
studyDataset.ReferringPhysicianName = dataset.ReferringPhysicianName
studyDataset[self.retrieveURLTag] = pydicom.dataelem.DataElement(
Expand Down Expand Up @@ -163,7 +163,7 @@ def handleSeries(self, parsedURL, requestBody):
firstInstance = instances[0]
dataset = pydicom.dcmread(slicer.dicomDatabase.fileForInstance(firstInstance), stop_before_pixels=True)
seriesDataset = pydicom.dataset.Dataset()
seriesDataset.SpecificCharacterSet = [u'ISO_IR 100']
seriesDataset.SpecificCharacterSet = ['ISO_IR 100']
seriesDataset.Modality = dataset.Modality
seriesDataset.SeriesInstanceUID = dataset.SeriesInstanceUID
seriesDataset.SeriesNumber = dataset.SeriesNumber
Expand Down
Expand Up @@ -12,7 +12,7 @@
import slicer


class SlicerRequestHandler(object):
class SlicerRequestHandler():
"""Implements the Slicer REST api"""

def __init__(self, enableExec=False):
Expand Down Expand Up @@ -439,7 +439,7 @@ def getNRRD(self, volumeID):
supportedScalarTypes = ["short", "double"]
scalarType = imageData.GetScalarTypeAsString()
if scalarType not in supportedScalarTypes:
self.logMessage('Can only get volumes of types %s, not %s' % (str(supportedScalarTypes), scalarType))
self.logMessage(f'Can only get volumes of types {str(supportedScalarTypes)}, not {scalarType}')
self.logMessage('Converting to short, but may cause data loss.')
volumeArray = numpy.array(volumeArray, dtype='int16')
scalarType = 'short'
Expand Down
Expand Up @@ -3,7 +3,7 @@
import os


class StaticPagesRequestHandler(object):
class StaticPagesRequestHandler():
"""Serves static pages content (files) from the configured docroot
"""

Expand Down Expand Up @@ -56,6 +56,6 @@ def handleRequest(self, uri, requestBody):
fp = open(path, 'rb')
responseBody = fp.read()
fp.close()
except IOError:
except OSError:
responseBody = None
return contentType, responseBody

0 comments on commit 9f7b811

Please sign in to comment.