Skip to content

Commit 55f7428

Browse files
STY: Use f-strings where possible
These have been changed manually.
1 parent c37102b commit 55f7428

32 files changed

+103
-110
lines changed

docs/sphinxext/docscrape.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -326,8 +326,9 @@ def parse_item_name(text):
326326
description = line_match.group("desc")
327327
if line_match.group("trailing") and description:
328328
self._error_location(
329-
"Unexpected comma or period after function list at index %d of "
330-
'line "%s"' % (line_match.end("trailing"), line),
329+
"Unexpected comma or period after function list "
330+
f"at index {line_match.end('trailing')} of line "
331+
f'"{line}"',
331332
error=False,
332333
)
333334
if not description and line.startswith(" "):
@@ -414,8 +415,8 @@ def _parse(self):
414415
section = " ".join(section)
415416
if self.get(section):
416417
self._error_location(
417-
"The section %s appears twice in %s"
418-
% (section, "\n".join(self._doc._str))
418+
f"The section {section} appears twice "
419+
f"in {'\n'.join(self._doc._str)}"
419420
)
420421

421422
if section in ("Parameters", "Other Parameters", "Attributes", "Methods"):

docs/sphinxext/github.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def make_link_node(rawtext, app, type, slug, options):
3737
if not base.endswith('/'):
3838
base += '/'
3939
except AttributeError as err:
40-
raise ValueError('github_project_url configuration value is not set (%s)' % str(err))
40+
raise ValueError(f'github_project_url configuration value is not set ({err})')
4141

4242
ref = base + type + '/' + slug + '/'
4343
set_classes(options)
@@ -71,19 +71,19 @@ def ghissue_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
7171
except ValueError:
7272
msg = inliner.reporter.error(
7373
'GitHub issue number must be a number greater than or equal to 1; '
74-
'"%s" is invalid.' % text, line=lineno)
74+
f'"{text}" is invalid.', line=lineno)
7575
prb = inliner.problematic(rawtext, rawtext, msg)
7676
return [prb], [msg]
7777
app = inliner.document.settings.env.app
78-
#app.info('issue %r' % text)
78+
#app.info(f'issue {text!r}')
7979
if 'pull' in name.lower():
8080
category = 'pull'
8181
elif 'issue' in name.lower():
8282
category = 'issues'
8383
else:
8484
msg = inliner.reporter.error(
8585
'GitHub roles include "ghpull" and "ghissue", '
86-
'"%s" is invalid.' % name, line=lineno)
86+
f'"{name}" is invalid.', line=lineno)
8787
prb = inliner.problematic(rawtext, rawtext, msg)
8888
return [prb], [msg]
8989
node = make_link_node(rawtext, app, category, str(issue_num), options)
@@ -105,7 +105,7 @@ def ghuser_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
105105
:param content: The directive content for customization.
106106
"""
107107
app = inliner.document.settings.env.app
108-
#app.info('user link %r' % text)
108+
#app.info(f'user link {text!r}')
109109
ref = 'https://www.github.com/' + text
110110
node = nodes.reference(rawtext, text, refuri=ref, **options)
111111
return [node], []
@@ -126,15 +126,15 @@ def ghcommit_role(name, rawtext, text, lineno, inliner, options={}, content=[]):
126126
:param content: The directive content for customization.
127127
"""
128128
app = inliner.document.settings.env.app
129-
#app.info('user link %r' % text)
129+
#app.info(f'user link {text!r}')
130130
try:
131131
base = app.config.github_project_url
132132
if not base:
133133
raise AttributeError
134134
if not base.endswith('/'):
135135
base += '/'
136136
except AttributeError as err:
137-
raise ValueError('github_project_url configuration value is not set (%s)' % str(err))
137+
raise ValueError(f'github_project_url configuration value is not set ({err})')
138138

139139
ref = base + text
140140
node = nodes.reference(rawtext, text[:6], refuri=ref, **options)

docs/sphinxext/math_dollar.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def dollars_to_math(source):
3333
def repl(matchobj):
3434
global _data
3535
s = matchobj.group(0)
36-
t = "___XXX_REPL_%d___" % len(_data)
36+
t = f"___XXX_REPL_{len(_data)}___"
3737
_data[t] = s
3838
return t
3939
s = re.sub(r"({[^{}$]*\$[^{}$]*\$[^{}]*})", repl, s)

niworkflows/__about__.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,7 @@
2929
from datetime import datetime
3030

3131
__packagename__ = "niworkflows"
32-
__copyright__ = "Copyright {}, The NiPreps Developers".format(
33-
datetime.now().year
34-
)
32+
__copyright__ = f"Copyright {datetime.now().year}, The NiPreps Developers"
3533
__credits__ = [
3634
"Oscar Esteban",
3735
"Ross Blair",

niworkflows/anat/ants.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -721,19 +721,19 @@ def init_atropos_wf(
721721

722722
# De-pad
723723
depad_mask = pe.Node(
724-
ImageMath(operation="PadImage", op2="-%d" % padding), name="23_depad_mask"
724+
ImageMath(operation="PadImage", op2=f"-{padding}"), name="23_depad_mask"
725725
)
726726
depad_segm = pe.Node(
727-
ImageMath(operation="PadImage", op2="-%d" % padding), name="24_depad_segm"
727+
ImageMath(operation="PadImage", op2=f"-{padding}"), name="24_depad_segm"
728728
)
729729
depad_gm = pe.Node(
730-
ImageMath(operation="PadImage", op2="-%d" % padding), name="25_depad_gm"
730+
ImageMath(operation="PadImage", op2=f"-{padding}"), name="25_depad_gm"
731731
)
732732
depad_wm = pe.Node(
733-
ImageMath(operation="PadImage", op2="-%d" % padding), name="26_depad_wm"
733+
ImageMath(operation="PadImage", op2=f"-{padding}"), name="26_depad_wm"
734734
)
735735
depad_csf = pe.Node(
736-
ImageMath(operation="PadImage", op2="-%d" % padding), name="27_depad_csf"
736+
ImageMath(operation="PadImage", op2=f"-{padding}"), name="27_depad_csf"
737737
)
738738

739739
msk_conform = pe.Node(niu.Function(function=_conform_mask), name="msk_conform")
@@ -1061,7 +1061,7 @@ def _select_labels(in_segm, labels):
10611061
for label in labels:
10621062
newnii = nii.__class__(np.uint8(label_data == label), nii.affine, nii.header)
10631063
newnii.set_data_dtype("uint8")
1064-
out_file = fname_presuffix(in_segm, suffix="_class-%02d" % label, newpath=cwd)
1064+
out_file = fname_presuffix(in_segm, suffix=f"_class-{label:%02d}", newpath=cwd)
10651065
newnii.to_filename(out_file)
10661066
out_files.append(out_file)
10671067
return out_files

niworkflows/data/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ class Loader:
110110
.. automethod:: cached
111111
"""
112112

113-
def __init__(self, anchor: Union[str, ModuleType]):
113+
def __init__(self, anchor: str | ModuleType):
114114
self._anchor = anchor
115115
self.files = files(anchor)
116116
self.exit_stack = ExitStack()

niworkflows/func/tests/test_util.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,11 +85,10 @@
8585
parameters = zip(bold_datasets, exp_masks)
8686

8787
if not bold_datasets:
88+
_folder_contents = "\n".join([str(p) for p in datapath.glob("ds*/*.nii.gz")])
8889
raise RuntimeError(
8990
f"Data folder <{datapath}> was provided, but no images were found. "
90-
"Folder contents:\n{}".format(
91-
"\n".join([str(p) for p in datapath.glob("ds*/*.nii.gz")])
92-
)
91+
f"Folder contents:\n{_folder_contents}"
9392
)
9493

9594

niworkflows/interfaces/bids.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -857,8 +857,7 @@ def _run_interface(self, runtime):
857857
for fname in self._fields:
858858
if not self._undef_fields and fname not in metadata:
859859
raise KeyError(
860-
'Metadata field "%s" not found for file %s'
861-
% (fname, self.inputs.in_file)
860+
f'Metadata field "{fname}" not found for file {self.inputs.in_file}'
862861
)
863862
self._results[fname] = metadata.get(fname, Undefined)
864863
return runtime
@@ -944,7 +943,7 @@ def _run_interface(self, runtime):
944943
if dest.exists():
945944
continue
946945
else:
947-
raise FileNotFoundError("Expected to find '%s' to copy" % source)
946+
raise FileNotFoundError(f"Expected to find '{source}' to copy")
948947

949948
if (
950949
space == 'fsaverage'

niworkflows/interfaces/confounds.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -298,13 +298,13 @@ def spike_regressors(
298298
mask = reduce((lambda x, y: x | y), mask.values())
299299

300300
for lag in lags:
301-
mask = set([m + lag for m in mask]) | mask
301+
mask = {m + lag for m in mask} | mask
302302

303303
mask = mask.intersection(indices)
304304
if minimum_contiguous is not None:
305305
post_final = data.shape[0] + 1
306-
epoch_length = np.diff(sorted(mask | set([-1, post_final]))) - 1
307-
epoch_end = sorted(mask | set([post_final]))
306+
epoch_length = np.diff(sorted(mask | {-1, post_final})) - 1
307+
epoch_end = sorted(mask | {post_final})
308308
for end, length in zip(epoch_end, epoch_length):
309309
if length < minimum_contiguous:
310310
mask = mask | set(range(end - length, end))
@@ -357,7 +357,7 @@ def temporal_derivatives(order, variables, data):
357357
if 0 in order:
358358
data_deriv[0] = data[variables]
359359
variables_deriv[0] = variables
360-
order = set(order) - set([0])
360+
order = set(order) - {0}
361361
for o in order:
362362
variables_deriv[o] = [f"{v}_derivative{o}" for v in variables]
363363
data_deriv[o] = np.tile(np.nan, data[variables].shape)
@@ -400,7 +400,7 @@ def exponential_terms(order, variables, data):
400400
if 1 in order:
401401
data_exp[1] = data[variables]
402402
variables_exp[1] = variables
403-
order = set(order) - set([1])
403+
order = set(order) - {1}
404404
for o in order:
405405
variables_exp[o] = [f"{v}_power{o}" for v in variables]
406406
data_exp[o] = data[variables] ** o

niworkflows/interfaces/freesurfer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ def cmdline(self):
139139
if source is None:
140140
return cmd
141141

142-
return "cp {} {}".format(source, self._list_outputs()["out_file"])
142+
return f"cp {source} {self._list_outputs()['out_file']}"
143143

144144

145145
class _FSInjectBrainExtractedInputSpec(BaseInterfaceInputSpec):

0 commit comments

Comments
 (0)