Skip to content

Commit b04228a

Browse files
committed
STY: Make use of f-strings extensive
Make use of f-strings extensive: prefer using f-strings for string interpolation and formatting instead of the modulo operator and the `str.format()` method. f-strings have become the preferred method for Python string formatting since their introduction in Python 3.6: https://peps.python.org/pep-0498/ The code becomes more concise and readable.
1 parent 8465bb2 commit b04228a

File tree

15 files changed

+84
-129
lines changed

15 files changed

+84
-129
lines changed

.maint/paper_author_list.py

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def _aslist(inlist):
3737
aff_indexes = [
3838
", ".join(
3939
[
40-
"%d" % (affiliations.index(a) + 1)
40+
f"{affiliations.index(a) + 1}"
4141
for a in _aslist(author.get("affiliation", "Unaffiliated"))
4242
]
4343
)
@@ -51,20 +51,11 @@ def _aslist(inlist):
5151
file=sys.stderr,
5252
)
5353

54-
print("Authors (%d):" % len(hits))
55-
print(
56-
"%s."
57-
% "; ".join(
58-
[
59-
"%s \\ :sup:`%s`\\ " % (i["name"], idx)
60-
for i, idx in zip(hits, aff_indexes)
61-
]
62-
)
54+
print(f"Authors ({len(hits)}):")
55+
authors = "; ".join(
56+
f"{i['name']} \\ :sup:`{idx}`\\ " for i, idx in zip(hits, aff_indexes)
6357
)
58+
print(f"{authors}.")
6459

65-
print(
66-
"\n\nAffiliations:\n%s"
67-
% "\n".join(
68-
["{0: >2}. {1}".format(i + 1, a) for i, a in enumerate(affiliations)]
69-
)
70-
)
60+
lines = '\n'.join(f'{i + 1: >2}. {a}' for i, a in enumerate(affiliations))
61+
print(f'\n\nAffiliations:\n{lines}')

.maint/update_zenodo.py

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -82,11 +82,11 @@ def get_git_lines(fname="line-contributors.txt"):
8282

8383
if not lines:
8484
raise RuntimeError(
85-
"""\
86-
Could not find line-contributors from git repository.%s"""
87-
% """ \
88-
git-line-summary not found, please install git-extras. """
89-
* (git_line_summary_path is None)
85+
f"""\
86+
Could not find line-contributors from git repository.{
87+
' git-line-summary not found, please install git-extras.'
88+
* (git_line_summary_path is None)
89+
}"""
9090
)
9191
return [" ".join(line.strip().split()[1:-1]) for line in lines if "%" in line]
9292

@@ -114,11 +114,10 @@ def get_git_lines(fname="line-contributors.txt"):
114114
zenodo["creators"] = zen_creators
115115
zenodo["contributors"] = zen_contributors
116116

117-
misses = set(miss_creators).intersection(miss_contributors)
118-
if misses:
117+
missing = {*miss_creators} & {*miss_contributors}
118+
if missing:
119119
print(
120-
"Some people made commits, but are missing in .maint/ "
121-
f"files: {', '.join(misses)}",
120+
f'Some people made commits, but are missing in .maint/ files: {", ".join(sorted(missing))}.',
122121
file=sys.stderr,
123122
)
124123

@@ -134,4 +133,4 @@ def get_git_lines(fname="line-contributors.txt"):
134133
if isinstance(creator["affiliation"], list):
135134
creator["affiliation"] = creator["affiliation"][0]
136135

137-
zenodo_file.write_text("%s\n" % json.dumps(zenodo, indent=2))
136+
zenodo_file.write_text(f"{json.dumps(zenodo, indent=2)}\n")

dmriprep/__about__.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,6 @@
3434
)
3535
__url__ = "https://github.com/nipreps/dmriprep"
3636

37-
DOWNLOAD_URL = "https://github.com/nipreps/{name}/archive/{ver}.tar.gz".format(
38-
name=__packagename__, ver=__version__
39-
)
37+
DOWNLOAD_URL = f"https://github.com/nipreps/{__packagename__}/archive/{__version__}.tar.gz"
4038

4139
__ga_id__ = "UA-156165436-1"

dmriprep/_version.py

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -86,20 +86,20 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
8686
if e.errno == errno.ENOENT:
8787
continue
8888
if verbose:
89-
print("unable to run %s" % dispcmd)
89+
print(f"unable to run {dispcmd}")
9090
print(e)
9191
return None, None
9292
else:
9393
if verbose:
94-
print("unable to find command, tried %s" % (commands,))
94+
print(f"unable to find command, tried {commands}")
9595
return None, None
9696
stdout = p.communicate()[0].strip()
9797
if sys.version_info[0] >= 3:
9898
stdout = stdout.decode()
9999
if p.returncode != 0:
100100
if verbose:
101-
print("unable to run %s (error)" % dispcmd)
102-
print("stdout was %s" % stdout)
101+
print(f"unable to run {dispcmd} (error)")
102+
print(f"stdout was {stdout}")
103103
return None, p.returncode
104104
return stdout, p.returncode
105105

@@ -124,8 +124,7 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
124124
root = os.path.dirname(root) # up a level
125125

126126
if verbose:
127-
print("Tried directories %s but none started with prefix %s" %
128-
(str(rootdirs), parentdir_prefix))
127+
print(f"Tried directories {rootdirs} but none started with prefix {parentdir_prefix}")
129128
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
130129

131130

@@ -192,15 +191,15 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
192191
# "stabilization", as well as "HEAD" and "master".
193192
tags = set([r for r in refs if re.search(r'\d', r)])
194193
if verbose:
195-
print("discarding '%s', no digits" % ",".join(refs - tags))
194+
print(f"discarding '{','.join(refs - tags)}', no digits")
196195
if verbose:
197-
print("likely tags: %s" % ",".join(sorted(tags)))
196+
print(f"likely tags: {','.join(sorted(tags))}")
198197
for ref in sorted(tags):
199198
# sorting will prefer e.g., "2.0" over "2.0rc1"
200199
if ref.startswith(tag_prefix):
201200
r = ref[len(tag_prefix):]
202201
if verbose:
203-
print("picking %s" % r)
202+
print(f"picking {r}")
204203
return {"version": r,
205204
"full-revisionid": keywords["full"].strip(),
206205
"dirty": False, "error": None,
@@ -229,14 +228,14 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
229228
hide_stderr=True)
230229
if rc != 0:
231230
if verbose:
232-
print("Directory %s not under git control" % root)
231+
print(f"Directory {root} not under git control")
233232
raise NotThisMethod("'git rev-parse --git-dir' returned error")
234233

235234
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
236235
# if there isn't one, this yields HEX[-dirty] (no NUM)
237236
describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",
238237
"--always", "--long",
239-
"--match", "%s*" % tag_prefix],
238+
"--match", f"{tag_prefix}*"],
240239
cwd=root)
241240
# --long was added in git-1.5.5
242241
if describe_out is None:
@@ -269,18 +268,16 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
269268
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
270269
if not mo:
271270
# unparseable. Maybe git-describe is misbehaving?
272-
pieces["error"] = ("unable to parse git-describe output: '%s'"
273-
% describe_out)
271+
pieces["error"] = f"unable to parse git-describe output: '{describe_out}'"
274272
return pieces
275273

276274
# tag
277275
full_tag = mo.group(1)
278276
if not full_tag.startswith(tag_prefix):
279277
if verbose:
280-
fmt = "tag '%s' doesn't start with prefix '%s'"
281-
print(fmt % (full_tag, tag_prefix))
282-
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
283-
% (full_tag, tag_prefix))
278+
print(
279+
f"tag '{full_tag}' doesn't start with prefix '{tag_prefix}'")
280+
pieces["error"] = (f"tag '{full_tag}' doesn't start with prefix '{tag_prefix}'"
284281
return pieces
285282
pieces["closest-tag"] = full_tag[len(tag_prefix):]
286283

@@ -370,13 +367,13 @@ def render_pep440_post(pieces):
370367
if pieces["dirty"]:
371368
rendered += ".dev0"
372369
rendered += plus_or_dot(pieces)
373-
rendered += "g%s" % pieces["short"]
370+
rendered += f"g{pieces['short']}"
374371
else:
375372
# exception #1
376373
rendered = "0.post%d" % pieces["distance"]
377374
if pieces["dirty"]:
378375
rendered += ".dev0"
379-
rendered += "+g%s" % pieces["short"]
376+
rendered += f"+g{pieces['short']}"
380377
return rendered
381378

382379

@@ -467,7 +464,7 @@ def render(pieces, style):
467464
elif style == "git-describe-long":
468465
rendered = render_git_describe_long(pieces)
469466
else:
470-
raise ValueError("unknown style '%s'" % style)
467+
raise ValueError(f"unknown style '{style}'")
471468

472469
return {"version": rendered, "full-revisionid": pieces["long"],
473470
"dirty": pieces["dirty"], "error": None,

dmriprep/cli/parser.py

Lines changed: 17 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,7 @@ def _bids_filter(value):
7474
)
7575

7676
parser = ArgumentParser(
77-
description="dMRIPrep: dMRI PREProcessing workflows v{}".format(
78-
config.environment.version
79-
),
77+
description=f"dMRIPrep: dMRI PREProcessing workflows v{config.environment.version}",
8078
formatter_class=ArgumentDefaultsHelpFormatter,
8179
)
8280
PathExists = partial(_path_exists, parser=parser)
@@ -224,7 +222,7 @@ def _bids_filter(value):
224222
"--output-spaces",
225223
nargs="*",
226224
action=OutputReferencesAction,
227-
help="""\
225+
help=f"""\
228226
Standard and non-standard spaces to resample anatomical and diffusion images to. \
229227
Standard spaces may be specified by the form \
230228
``<SPACE>[:cohort-<label>][:res-<resolution>][...]``, where ``<SPACE>`` is \
@@ -236,8 +234,7 @@ def _bids_filter(value):
236234
Important to note, the ``res-*`` modifier does not define the resolution used for \
237235
the spatial normalization. To generate no DWI outputs (if that is intended for some reason), \
238236
use this option without specifying any spatial references. For further details, please check out \
239-
https://www.nipreps.org/dmriprep/en/%s/spaces.html"""
240-
% (currentv.base_version if is_release else "latest"),
237+
https://www.nipreps.org/dmriprep/en/{currentv.base_version if is_release else "latest"}/spaces.html"""
241238
)
242239
g_conf.add_argument(
243240
"--dwi2t1w-init",
@@ -388,24 +385,22 @@ def _bids_filter(value):
388385
latest = check_latest()
389386
if latest is not None and currentv < latest:
390387
print(
391-
"""\
392-
You are using dMRIPrep-%s, and a newer version of dMRIPrep is available: %s.
388+
f"""\
389+
You are using dMRIPrep-{currentv}, and a newer version of dMRIPrep is available: {latest}.
393390
Please check out our documentation about how and when to upgrade:
394-
https://dmriprep.readthedocs.io/en/latest/faq.html#upgrading"""
395-
% (currentv, latest),
391+
https://dmriprep.readthedocs.io/en/latest/faq.html#upgrading""",
396392
file=sys.stderr,
397393
)
398394

399395
_blist = is_flagged()
400396
if _blist[0]:
401397
_reason = _blist[1] or "unknown"
402398
print(
403-
"""\
404-
WARNING: Version %s of dMRIPrep (current) has been FLAGGED
405-
(reason: %s).
399+
f"""\
400+
WARNING: Version {config.environment.version} of dMRIPrep (current) has been FLAGGED
401+
(reason: {_reason}).
406402
That means some severe flaw was found in it and we strongly
407-
discourage its usage."""
408-
% (config.environment.version, _reason),
403+
discourage its usage.""",
409404
file=sys.stderr,
410405
)
411406

@@ -459,10 +454,8 @@ def parse_args(args=None, namespace=None):
459454
# This may need to be revisited if people try to use batch plugins
460455
if 1 < config.nipype.nprocs < config.nipype.omp_nthreads:
461456
build_log.warning(
462-
"Per-process threads (--omp-nthreads=%d) exceed total "
463-
"threads (--nthreads/--n_cpus=%d)",
464-
config.nipype.omp_nthreads,
465-
config.nipype.nprocs,
457+
f"Per-process threads (--omp-nthreads={config.nipype.omp_nthreads}) exceed total "
458+
f"threads (--nthreads/--n_cpus={config.nipype.nprocs})",
466459
)
467460

468461
bids_dir = config.execution.bids_dir
@@ -477,20 +470,18 @@ def parse_args(args=None, namespace=None):
477470
if opts.clean_workdir and work_dir.exists():
478471
from niworkflows.utils.misc import clean_directory
479472

480-
build_log.log("Clearing previous dMRIPrep working directory: %s", work_dir)
473+
build_log.log(f"Clearing previous dMRIPrep working directory: {work_dir}")
481474
if not clean_directory(work_dir):
482475
build_log.warning(
483-
"Could not clear all contents of working directory: %s", work_dir
476+
f"Could not clear all contents of working directory: {work_dir}"
484477
)
485478

486479
# Ensure input and output folders are not the same
487480
if output_dir == bids_dir:
481+
ver = version.split("+")[0]
488482
parser.error(
489483
"The selected output folder is the same as the input BIDS folder. "
490-
"Please modify the output path (suggestion: %s)."
491-
% bids_dir
492-
/ "derivatives"
493-
/ ("dmriprep-%s" % version.split("+")[0])
484+
f'Please modify the output path (suggestion: {bids_dir / 'derivatives' / f'dmriprep-{ver}'}).'
494485
)
495486

496487
if bids_dir in work_dir.parents:
@@ -529,7 +520,7 @@ def parse_args(args=None, namespace=None):
529520
if missing_subjects:
530521
parser.error(
531522
"One or more participant labels were not found in the BIDS directory: "
532-
"%s." % ", ".join(missing_subjects)
523+
f"{', '.join(missing_subjects)}."
533524
)
534525

535526
config.execution.participant_label = sorted(participant_label)

dmriprep/cli/run.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ def main():
103103
config.loggers.workflow.log(
104104
15,
105105
"\n".join(
106-
["dMRIPrep config:"] + ["\t\t%s" % s for s in config.dumps().splitlines()]
106+
["dMRIPrep config:"] + [f"\t\t{s}" for s in config.dumps().splitlines()]
107107
),
108108
)
109109
config.loggers.workflow.log(25, "dMRIPrep started!")
@@ -113,7 +113,7 @@ def main():
113113
except Exception as e:
114114
if not config.execution.notrack:
115115
popylar.track_event(__ga_id__, "run", "error")
116-
config.loggers.workflow.critical("dMRIPrep failed: %s", e)
116+
config.loggers.workflow.critical(f"dMRIPrep failed: {e}")
117117
raise
118118
else:
119119
config.loggers.workflow.log(25, "dMRIPrep finished successfully!")

dmriprep/cli/tests/test_parser.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -109,13 +109,10 @@ def _mock_check_latest(*args, **kwargs):
109109
_build_parser()
110110
captured = capsys.readouterr().err
111111

112-
msg = """\
113-
You are using dMRIPrep-%s, and a newer version of dMRIPrep is available: %s.
112+
msg = f"""\
113+
You are using dMRIPrep-{current}, and a newer version of dMRIPrep is available: {latest}.
114114
Please check out our documentation about how and when to upgrade:
115-
https://dmriprep.readthedocs.io/en/latest/faq.html#upgrading""" % (
116-
current,
117-
latest,
118-
)
115+
https://dmriprep.readthedocs.io/en/latest/faq.html#upgrading"""
119116

120117
assert (msg in captured) is expectation
121118

dmriprep/cli/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def check_latest():
7474
if latest is not None:
7575
try:
7676
cachefile.write_text(
77-
"|".join(("%s" % latest, datetime.now().strftime(DATE_FMT)))
77+
"|".join((f"{latest}", datetime.now().strftime(DATE_FMT)))
7878
)
7979
except Exception:
8080
pass

0 commit comments

Comments
 (0)