Skip to content

Commit b10fbc1

Browse files
committed
STY: Old formatting to f-strings (PEP-498)
%, '{}'.format -> f'{}' F-strings are supported from py3.6 which is nibabel's minimal python version (up-to-date). Was done with: https://github.com/ikamensh/flynt Excluding versioneer.py First commit changes were reviewed manually
1 parent b48fb17 commit b10fbc1

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

87 files changed

+277
-331
lines changed

bin/nib-dicomfs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@
1212
from nibabel.cmdline.dicomfs import main
1313

1414
if __name__ == '__main__':
15-
main()
15+
main()

doc/source/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@
9292

9393
# General information about the project.
9494
project = u'NiBabel'
95-
copyright = u'2006-2020, %(maintainer)s <%(author_email)s>' % metadata
95+
copyright = f"2006-2020, {metadata['maintainer']} <{metadata['author_email']}>"
9696

9797
# The version info for the project you're documenting, acts as replacement for
9898
# |version| and |release|, also used in various other places throughout the

doc/source/devel/register_me.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def main():
4040
dsource.set(name, version, OUR_PATH)
4141
dsource.write(file(ini_fname, 'wt'))
4242

43-
print('Registered package %s, %s to %s' % (name, version, ini_fname))
43+
print(f'Registered package {name}, {version} to {ini_fname}')
4444

4545

4646
if __name__ == '__main__':

doc/tools/apigen.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -342,8 +342,7 @@ def _survives_exclude(self, matchstr, match_type):
342342
elif match_type == 'package':
343343
patterns = self.package_skip_patterns
344344
else:
345-
raise ValueError('Cannot interpret match type "%s"'
346-
% match_type)
345+
raise ValueError(f'Cannot interpret match type "{match_type}"')
347346
# Match to URI without package name
348347
L = len(self.package_name)
349348
if matchstr[:L] == self.package_name:
@@ -424,7 +423,7 @@ def write_modules_api(self, modules, outdir):
424423
written_modules = []
425424

426425
for ulm, mods in module_by_ulm.items():
427-
print("Generating docs for %s:" % ulm)
426+
print(f"Generating docs for {ulm}:")
428427
document_head = []
429428
document_body = []
430429

@@ -505,5 +504,5 @@ def write_index(self, outdir, froot='gen', relative_to=None):
505504
w("=" * len(title) + "\n\n")
506505
w('.. toctree::\n\n')
507506
for f in self.written_modules:
508-
w(' %s\n' % os.path.join(relpath, f))
507+
w(f' {os.path.join(relpath, f)}\n')
509508
idx.close()

doc/tools/build_modref_templates.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919

2020
def abort(error):
21-
print('*WARNING* API documentation not generated: %s' % error)
21+
print(f'*WARNING* API documentation not generated: {error}')
2222
exit(1)
2323

2424

nibabel/_version.py

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

@@ -201,9 +201,9 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
201201
# "stabilization", as well as "HEAD" and "master".
202202
tags = set([r for r in refs if re.search(r'\d', r)])
203203
if verbose:
204-
print("discarding '%s', no digits" % ",".join(refs - tags))
204+
print(f"discarding '{','.join(refs - tags)}', no digits")
205205
if verbose:
206-
print("likely tags: %s" % ",".join(sorted(tags)))
206+
print(f"likely tags: {','.join(sorted(tags))}")
207207
for ref in sorted(tags):
208208
# sorting will prefer e.g. "2.0" over "2.0rc1"
209209
if ref.startswith(tag_prefix):
@@ -214,7 +214,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
214214
if not re.match(r'\d', r):
215215
continue
216216
if verbose:
217-
print("picking %s" % r)
217+
print(f"picking {r}")
218218
return {"version": r,
219219
"full-revisionid": keywords["full"].strip(),
220220
"dirty": False, "error": None,
@@ -243,14 +243,14 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
243243
hide_stderr=True)
244244
if rc != 0:
245245
if verbose:
246-
print("Directory %s not under git control" % root)
246+
print(f"Directory {root} not under git control")
247247
raise NotThisMethod("'git rev-parse --git-dir' returned error")
248248

249249
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
250250
# if there isn't one, this yields HEX[-dirty] (no NUM)
251251
describe_out, rc = run_command(GITS, ["describe", "--tags", "--dirty",
252252
"--always", "--long",
253-
"--match", "%s*" % tag_prefix],
253+
"--match", f"{tag_prefix}*"],
254254
cwd=root)
255255
# --long was added in git-1.5.5
256256
if describe_out is None:
@@ -283,8 +283,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
283283
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
284284
if not mo:
285285
# unparseable. Maybe git-describe is misbehaving?
286-
pieces["error"] = ("unable to parse git-describe output: '%s'"
287-
% describe_out)
286+
pieces["error"] = (f"unable to parse git-describe output: '{describe_out}'")
288287
return pieces
289288

290289
# tag
@@ -384,13 +383,13 @@ def render_pep440_post(pieces):
384383
if pieces["dirty"]:
385384
rendered += ".dev0"
386385
rendered += plus_or_dot(pieces)
387-
rendered += "g%s" % pieces["short"]
386+
rendered += f"g{pieces['short']}"
388387
else:
389388
# exception #1
390389
rendered = "0.post%d" % pieces["distance"]
391390
if pieces["dirty"]:
392391
rendered += ".dev0"
393-
rendered += "+g%s" % pieces["short"]
392+
rendered += f"+g{pieces['short']}"
394393
return rendered
395394

396395

@@ -481,7 +480,7 @@ def render(pieces, style):
481480
elif style == "git-describe-long":
482481
rendered = render_git_describe_long(pieces)
483482
else:
484-
raise ValueError("unknown style '%s'" % style)
483+
raise ValueError(f"unknown style '{style}'")
485484

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

nibabel/analyze.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -571,16 +571,16 @@ def set_data_dtype(self, datatype):
571571
dt = np.dtype(dt)
572572
except TypeError:
573573
raise HeaderDataError(
574-
'data dtype "{0}" not recognized'.format(datatype))
574+
f'data dtype "{datatype}" not recognized')
575575
if dt not in self._data_type_codes:
576576
raise HeaderDataError(
577-
'data dtype "{0}" not supported'.format(datatype))
577+
f'data dtype "{datatype}" not supported')
578578
code = self._data_type_codes[dt]
579579
dtype = self._data_type_codes.dtype[code]
580580
# test for void, being careful of user-defined types
581581
if dtype.type is np.void and not dtype.fields:
582582
raise HeaderDataError(
583-
'data dtype "{0}" known but not supported'.format(datatype))
583+
f'data dtype "{datatype}" known but not supported')
584584
self._structarr['datatype'] = code
585585
self._structarr['bitpix'] = dtype.itemsize * 8
586586

@@ -632,8 +632,7 @@ def set_data_shape(self, shape):
632632
values_fit = np.all(dims[1:ndims + 1] == shape)
633633
# Error if we did not succeed setting dimensions
634634
if not values_fit:
635-
raise HeaderDataError('shape %s does not fit in dim datatype' %
636-
(shape,))
635+
raise HeaderDataError(f'shape {shape} does not fit in dim datatype')
637636
self._structarr['pixdim'][ndims + 1:] = 1.0
638637

639638
def get_base_affine(self):

nibabel/batteryrunners.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -291,8 +291,7 @@ def write_raise(self, stream, error_level=40, log_level=30):
291291
write the report to `stream`, otherwise we write nothing.
292292
"""
293293
if self.problem_level >= log_level:
294-
stream.write('Level %s: %s\n' %
295-
(self.problem_level, self.message))
294+
stream.write(f'Level {self.problem_level}: {self.message}\n')
296295
if self.problem_level and self.problem_level >= error_level:
297296
if self.error:
298297
raise self.error(self.problem_msg)

nibabel/benchmarks/bench_arrayproxy_slicing.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ def fmt_sliceobj(sliceobj):
9696
slcstr.append(s)
9797
else:
9898
slcstr.append(str(int(s * SHAPE[i])))
99-
return '[{}]'.format(', '.join(slcstr))
99+
return f"[{', '.join(slcstr)}]"
100100

101101
with InTemporaryDirectory():
102102

@@ -133,8 +133,7 @@ def fmt_sliceobj(sliceobj):
133133
have_igzip, keep_open, sliceobj = test
134134
seed = seeds[SLICEOBJS.index(sliceobj)]
135135

136-
print('Running test {} of {} ({})...'.format(
137-
ti + 1, len(tests), label))
136+
print(f'Running test {ti + 1} of {len(tests)} ({label})...')
138137

139138
# load uncompressed and compressed versions of the image
140139
img = nib.load(testfile, keep_file_open=keep_open)

nibabel/benchmarks/bench_fileslice.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
from ..tmpdirs import InTemporaryDirectory
2121

2222
SHAPE = (64, 64, 32, 100)
23-
ROW_NAMES = ['axis {0}, len {1}'.format(i, SHAPE[i])
23+
ROW_NAMES = [f'axis {i}, len {SHAPE[i]}'
2424
for i in range(len(SHAPE))]
2525
COL_NAMES = ['mid int',
2626
'step 1',
@@ -79,7 +79,7 @@ def my_table(title, times, base):
7979
print()
8080
print(rst_table(times, ROW_NAMES, COL_NAMES, title,
8181
val_fmt='{0[0]:3.2f} ({0[1]:3.2f})'))
82-
print('Base time: {0:3.2f}'.format(base))
82+
print(f'Base time: {base:3.2f}')
8383
if bytes:
8484
fobj = BytesIO()
8585
times, base = run_slices(fobj, repeat)

0 commit comments

Comments
 (0)