Skip to content

Commit dc49019

Browse files
committed
STYLE: Prefer modern f-strings formatting
```bash pip install flynt git ls-files '*.py' \ | xargs flynt ```
1 parent ff50ec4 commit dc49019

21 files changed

+57
-73
lines changed

bin/GenerateInputCSV_Datasethierarchy.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def main():
2121
datasetReader = DatasetHierarchyReader(inputDirectory, filetype=filetype)
2222
datasetHierarchyDict = datasetReader.ReadDatasetHierarchy()
2323

24-
print("Found %s patients, writing csv" % (str(len(datasetHierarchyDict.keys()))))
24+
print(f"Found {str(len(datasetHierarchyDict.keys()))} patients, writing csv")
2525

2626
try:
2727
with open(outputFile, "wb") as outFile:

bin/GenerateInputCSV_Filename.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ def main():
3636

3737
datasetHierarchyDict = scanpatients(inputDirectory, filetype)
3838

39-
print("Found %s patients, writing csv" % (len(datasetHierarchyDict.keys())))
39+
print(f"Found {len(datasetHierarchyDict.keys())} patients, writing csv")
4040

4141
try:
4242
with open(outputFile, "w") as outFile:
@@ -60,11 +60,11 @@ def main():
6060

6161
i_name = Study
6262
if i_idx > 0:
63-
i_name += " (%s)" % (str(i_idx + 1))
63+
i_name += f" ({str(i_idx + 1)})"
6464

6565
s_name = Reader
6666
if s_idx > 0:
67-
s_name += " (%s)" % (str(s_idx + 1))
67+
s_name += f" ({str(s_idx + 1)})"
6868

6969
cw.writerow(
7070
[patient, i_name, s_name, im_file, seg_file]

bin/testParams.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def main(paramsFile):
2626
% (params["featureClass"], params["imageType"], params["setting"])
2727
)
2828
except Exception as e:
29-
print("Parameter validation failed!\n%s" % e.message)
29+
print(f"Parameter validation failed!\n{e.message}")
3030

3131

3232
if __name__ == "__main__" and len(sys.argv) > 1:

examples/helloFeatureClass.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@
6868
print("Will calculate the following first order features: ")
6969
for f in firstOrderFeatures.enabledFeatures.keys():
7070
print(" ", f)
71-
print(getattr(firstOrderFeatures, "get%sFeatureValue" % f).__doc__)
71+
print(getattr(firstOrderFeatures, f"get{f}FeatureValue").__doc__)
7272

7373
print("Calculating first order features...")
7474
results = firstOrderFeatures.execute()
@@ -87,7 +87,7 @@
8787
print("Will calculate the following Shape features: ")
8888
for f in shapeFeatures.enabledFeatures.keys():
8989
print(" ", f)
90-
print(getattr(shapeFeatures, "get%sFeatureValue" % f).__doc__)
90+
print(getattr(shapeFeatures, f"get{f}FeatureValue").__doc__)
9191

9292
print("Calculating Shape features...")
9393
results = shapeFeatures.execute()
@@ -106,7 +106,7 @@
106106
print("Will calculate the following GLCM features: ")
107107
for f in glcmFeatures.enabledFeatures.keys():
108108
print(" ", f)
109-
print(getattr(glcmFeatures, "get%sFeatureValue" % f).__doc__)
109+
print(getattr(glcmFeatures, f"get{f}FeatureValue").__doc__)
110110

111111
print("Calculating GLCM features...")
112112
results = glcmFeatures.execute()
@@ -125,7 +125,7 @@
125125
print("Will calculate the following GLRLM features: ")
126126
for f in glrlmFeatures.enabledFeatures.keys():
127127
print(" ", f)
128-
print(getattr(glrlmFeatures, "get%sFeatureValue" % f).__doc__)
128+
print(getattr(glrlmFeatures, f"get{f}FeatureValue").__doc__)
129129

130130
print("Calculating GLRLM features...")
131131
results = glrlmFeatures.execute()
@@ -144,7 +144,7 @@
144144
print("Will calculate the following GLSZM features: ")
145145
for f in glszmFeatures.enabledFeatures.keys():
146146
print(" ", f)
147-
print(getattr(glszmFeatures, "get%sFeatureValue" % f).__doc__)
147+
print(getattr(glszmFeatures, f"get{f}FeatureValue").__doc__)
148148

149149
print("Calculating GLSZM features...")
150150
results = glszmFeatures.execute()
@@ -168,7 +168,7 @@
168168
logFirstorderFeatures.enableAllFeatures()
169169
results = logFirstorderFeatures.execute()
170170
for key, val in results.items():
171-
laplacianFeatureName = "{}_{}".format(imageTypeName, key)
171+
laplacianFeatureName = f"{imageTypeName}_{key}"
172172
print(" ", laplacianFeatureName, ":", val)
173173
#
174174
# Show FirstOrder features, calculated on a wavelet filtered image
@@ -186,5 +186,5 @@
186186
results = waveletFirstOrderFeaturs.execute()
187187
print("Calculated firstorder features with wavelet ", decompositionName)
188188
for key, val in results.items():
189-
waveletFeatureName = "{}_{}".format(str(decompositionName), key)
189+
waveletFeatureName = f"{str(decompositionName)}_{key}"
190190
print(" ", waveletFeatureName, ":", val)

examples/helloRadiomics.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,4 +63,4 @@
6363
featureVector = extractor.execute(imageName, maskName)
6464

6565
for featureName in featureVector.keys():
66-
print("Computed {}: {}".format(featureName, featureVector[featureName]))
66+
print(f"Computed {featureName}: {featureVector[featureName]}")

examples/helloRadiomicsWithSettings.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,10 @@
5151
]
5252
for f in features:
5353
print(f)
54-
print(getattr(featureClasses[cls], "get%sFeatureValue" % f).__doc__)
54+
print(getattr(featureClasses[cls], f"get{f}FeatureValue").__doc__)
5555

5656
print("Calculating features")
5757
featureVector = extractor.execute(imageName, maskName)
5858

5959
for featureName in featureVector.keys():
60-
print("Computed {}: {}".format(featureName, featureVector[featureName]))
60+
print(f"Computed {featureName}: {featureVector[featureName]}")

examples/helloVoxel.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -128,18 +128,14 @@ def __exit__(self, exc_type, exc_value, tb):
128128
]
129129
for f in features:
130130
print(f)
131-
print(getattr(featureClasses[cls], "get%sFeatureValue" % f).__doc__)
131+
print(getattr(featureClasses[cls], f"get{f}FeatureValue").__doc__)
132132

133133
print("Calculating features")
134134
featureVector = extractor.execute(imageName, maskName, voxelBased=True)
135135

136136
for featureName, featureValue in featureVector.items():
137137
if isinstance(featureValue, sitk.Image):
138-
sitk.WriteImage(featureValue, "{}_{}.nrrd".format(testCase, featureName))
139-
print(
140-
'Computed {}, stored as "{}_{}.nrrd"'.format(
141-
featureName, testCase, featureName
142-
)
143-
)
138+
sitk.WriteImage(featureValue, f"{testCase}_{featureName}.nrrd")
139+
print(f'Computed {featureName}, stored as "{testCase}_{featureName}.nrrd"')
144140
else:
145-
print("{}: {}".format(featureName, featureValue))
141+
print(f"{featureName}: {featureValue}")

labs/pyradiomics-dcm/pyradiomics-dcm.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,7 @@ def addMeasurement(
359359
return
360360

361361
try:
362-
measurement["value"] = "%E" % Decimal(float(value))
362+
measurement["value"] = f"{Decimal(float(value)):E}"
363363
except Exception as e:
364364
scriptlogger.error("Exception formatting %s as Decimal: %s", value, str(e))
365365
scriptlogger.error("type of value: %s", type(value))

radiomics/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ def getTestCase(testCase, dataDirectory=None):
159159
testCase = testCase[:-3]
160160

161161
if testCase not in testCases:
162-
raise ValueError('Testcase "%s" not recognized!' % testCase)
162+
raise ValueError(f'Testcase "{testCase}" not recognized!')
163163

164164
logger.debug("Getting test case %s", testCase)
165165

@@ -169,8 +169,8 @@ def getTestCase(testCase, dataDirectory=None):
169169
'No data directory specified, using temporary directory "%s"', dataDirectory
170170
)
171171

172-
im_name = "%s_image.nrrd" % testCase
173-
ma_name = "{}_label{}.nrrd".format(testCase, "_2D" if label2D else "")
172+
im_name = f"{testCase}_image.nrrd"
173+
ma_name = f"{testCase}_label{'_2D' if label2D else ''}.nrrd"
174174

175175
def get_or_download(fname):
176176
target = os.path.join(dataDirectory, fname)

radiomics/base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ def _calculateFeatures(self, voxelCoordinates=None):
259259
if enabled:
260260
try:
261261
# Use getattr to get the feature calculation methods, then use '()' to evaluate those methods
262-
yield True, feature, getattr(self, "get%sFeatureValue" % feature)()
262+
yield True, feature, getattr(self, f"get{feature}FeatureValue")()
263263
except DeprecationWarning as deprecatedFeature:
264264
# Add a debug log message, as a warning is usually shown and would entail a too verbose output
265265
self.logger.debug(

0 commit comments

Comments
 (0)