Skip to content

Commit 0ba55d4

Browse files
authored
Merge pull request #919 from jond01/fstrings
STY: Old formatting to f-strings (PEP-498)
2 parents 7a7a913 + 0dd06ee commit 0ba55d4

File tree

96 files changed

+449
-575
lines changed

Some content is hidden

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

96 files changed

+449
-575
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: 3 additions & 2 deletions
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
@@ -206,7 +206,8 @@
206206
#html_use_smartypants = True
207207

208208
# Custom sidebar templates, maps document names to template names.
209-
html_sidebars = {'index': ['localtoc.html', 'relations.html', 'sourcelink.html', 'indexsidebar.html', 'searchbox.html', 'reggie.html']}
209+
html_sidebars = {'index': ['localtoc.html', 'relations.html', 'sourcelink.html',
210+
'indexsidebar.html', 'searchbox.html', 'reggie.html']}
210211

211212
# Additional templates that should be rendered to pages, maps page names to
212213
# template names.

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/analyze.py

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -394,11 +394,9 @@ def from_header(klass, header=None, check=True):
394394
try:
395395
obj.set_data_dtype(orig_code)
396396
except HeaderDataError:
397-
raise HeaderDataError('Input header %s has datatype %s but '
398-
'output header %s does not support it'
399-
% (header.__class__,
400-
header.get_value_label('datatype'),
401-
klass))
397+
raise HeaderDataError(f"Input header {header.__class__} has "
398+
f"datatype {header.get_value_label('datatype')} "
399+
f"but output header {klass} does not support it")
402400
obj.set_data_dtype(header.get_data_dtype())
403401
obj.set_data_shape(header.get_data_shape())
404402
obj.set_zooms(header.get_zooms())
@@ -571,16 +569,16 @@ def set_data_dtype(self, datatype):
571569
dt = np.dtype(dt)
572570
except TypeError:
573571
raise HeaderDataError(
574-
'data dtype "{0}" not recognized'.format(datatype))
572+
f'data dtype "{datatype}" not recognized')
575573
if dt not in self._data_type_codes:
576574
raise HeaderDataError(
577-
'data dtype "{0}" not supported'.format(datatype))
575+
f'data dtype "{datatype}" not supported')
578576
code = self._data_type_codes[dt]
579577
dtype = self._data_type_codes.dtype[code]
580578
# test for void, being careful of user-defined types
581579
if dtype.type is np.void and not dtype.fields:
582580
raise HeaderDataError(
583-
'data dtype "{0}" known but not supported'.format(datatype))
581+
f'data dtype "{datatype}" known but not supported')
584582
self._structarr['datatype'] = code
585583
self._structarr['bitpix'] = dtype.itemsize * 8
586584

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

639636
def get_base_affine(self):

nibabel/arrayproxy.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -255,8 +255,8 @@ def _should_keep_file_open(self, file_like, keep_file_open):
255255
if keep_file_open is None:
256256
keep_file_open = KEEP_FILE_OPEN_DEFAULT
257257
if keep_file_open not in (True, False):
258-
raise ValueError("nibabel.arrayproxy.KEEP_FILE_OPEN_DEFAULT must be boolean. "
259-
"Found: {}".format(keep_file_open))
258+
raise ValueError("nibabel.arrayproxy.KEEP_FILE_OPEN_DEFAULT "
259+
f"must be boolean. Found: {keep_file_open}")
260260
elif keep_file_open not in (True, False):
261261
raise ValueError('keep_file_open must be one of {None, True, False}')
262262

@@ -412,8 +412,7 @@ def reshape(self, shape):
412412
shape = tuple(unknown_size if e == -1 else e for e in shape)
413413

414414
if np.prod(shape) != size:
415-
raise ValueError("cannot reshape array of size {:d} into shape "
416-
"{!s}".format(size, shape))
415+
raise ValueError(f"cannot reshape array of size {size:d} into shape {shape!s}")
417416
return self.__class__(file_like=self.file_like,
418417
spec=(shape, self._dtype, self._offset,
419418
self._slope, self._inter),

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: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -96,12 +96,11 @@ 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

103-
print('Generating test data... ({} MB)'.format(
104-
int(round(np.prod(SHAPE) * 4 / 1048576.))))
103+
print(f'Generating test data... ({int(round(np.prod(SHAPE) * 4 / 1048576.0))} MB)')
105104

106105
data = np.array(np.random.random(SHAPE), dtype=np.float32)
107106

@@ -133,8 +132,7 @@ def fmt_sliceobj(sliceobj):
133132
have_igzip, keep_open, sliceobj = test
134133
seed = seeds[SLICEOBJS.index(sliceobj)]
135134

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

139137
# load uncompressed and compressed versions of the image
140138
img = nib.load(testfile, keep_file_open=keep_open)
@@ -181,8 +179,7 @@ def testfunc():
181179
data[:, 2] = np.nan
182180
data[:, 3] = [r[5] - r[6] for r in results]
183181

184-
rowlbls = ['Type {}, keep_open {}, slice {}'.format(
185-
r[0], r[1], fmt_sliceobj(r[2])) for r in results]
182+
rowlbls = [f'Type {r[0]}, keep_open {r[1]}, slice {fmt_sliceobj(r[2])}' for r in results]
186183
collbls = ['Time', 'Baseline time', 'Time ratio', 'Memory deviation']
187184

188185
print(rst_table(data, rowlbls, collbls))

nibabel/benchmarks/bench_fileslice.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +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])
24-
for i in range(len(SHAPE))]
23+
ROW_NAMES = [f'axis {i}, len {dim}' for i, dim in enumerate(SHAPE)]
2524
COL_NAMES = ['mid int',
2625
'step 1',
2726
'half step 1',
@@ -79,7 +78,7 @@ def my_table(title, times, base):
7978
print()
8079
print(rst_table(times, ROW_NAMES, COL_NAMES, title,
8180
val_fmt='{0[0]:3.2f} ({0[1]:3.2f})'))
82-
print('Base time: {0:3.2f}'.format(base))
81+
print(f'Base time: {base:3.2f}')
8382
if bytes:
8483
fobj = BytesIO()
8584
times, base = run_slices(fobj, repeat)

0 commit comments

Comments
 (0)