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

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)

nibabel/benchmarks/bench_streamlines.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,16 +44,14 @@ def bench_load_trk():
4444
streamlines_old = [d[0] - 0.5
4545
for d in tv.read(trk_file, points_space="rasmm")[0]]
4646
mtime_old = measure('tv.read(trk_file, points_space="rasmm")', repeat)
47-
print("Old: Loaded {:,} streamlines in {:6.2f}".format(NB_STREAMLINES,
48-
mtime_old))
47+
print(f"Old: Loaded {NB_STREAMLINES:,} streamlines in {mtime_old:6.2f}")
4948

5049
trk = nib.streamlines.load(trk_file, lazy_load=False)
5150
streamlines_new = trk.streamlines
5251
mtime_new = measure('nib.streamlines.load(trk_file, lazy_load=False)',
5352
repeat)
54-
print("\nNew: Loaded {:,} streamlines in {:6.2}".format(NB_STREAMLINES,
55-
mtime_new))
56-
print("Speedup of {:.2f}".format(mtime_old / mtime_new))
53+
print(f"\nNew: Loaded {NB_STREAMLINES:,} streamlines in {mtime_new:6.2}")
54+
print(f"Speedup of {mtime_old / mtime_new:.2f}")
5755
for s1, s2 in zip(streamlines_new, streamlines_old):
5856
assert_array_equal(s1, s2)
5957

@@ -81,7 +79,7 @@ def bench_load_trk():
8179
repeat)
8280
msg = "New: Loaded {:,} streamlines with scalars in {:6.2f}"
8381
print(msg.format(NB_STREAMLINES, mtime_new))
84-
print("Speedup of {:2f}".format(mtime_old / mtime_new))
82+
print(f"Speedup of {mtime_old / mtime_new:2f}")
8583
for s1, s2 in zip(scalars_new, scalars_old):
8684
assert_array_equal(s1, s2)
8785

nibabel/benchmarks/butils.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@
77
def print_git_title(title):
88
""" Prints title string with git hash if possible, and underline
99
"""
10-
title = '{0} for git revision {1}'.format(
11-
title,
12-
get_info()['commit_hash'])
10+
title = f"{title} for git revision {get_info()['commit_hash']}"
1311
print(title)
1412
print('-' * len(title))

nibabel/brikhead.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -115,22 +115,20 @@ def _unpack_var(var):
115115
"""
116116

117117
err_msg = ('Please check HEAD file to ensure it is AFNI compliant. '
118-
'Offending attribute:\n%s' % var)
118+
f'Offending attribute:\n{var}')
119119
atype, aname = TYPE_RE.findall(var), NAME_RE.findall(var)
120120
if len(atype) != 1:
121-
raise AFNIHeaderError('Invalid attribute type entry in HEAD file. '
122-
'%s' % err_msg)
121+
raise AFNIHeaderError(f'Invalid attribute type entry in HEAD file. {err_msg}')
123122
if len(aname) != 1:
124-
raise AFNIHeaderError('Invalid attribute name entry in HEAD file. '
125-
'%s' % err_msg)
123+
raise AFNIHeaderError(f'Invalid attribute name entry in HEAD file. {err_msg}')
126124
atype = _attr_dic.get(atype[0], str)
127125
attr = ' '.join(var.strip().splitlines()[3:])
128126
if atype is not str:
129127
try:
130128
attr = [atype(f) for f in attr.split()]
131129
except ValueError:
132-
raise AFNIHeaderError('Failed to read variable from HEAD file due '
133-
'to improper type casting. %s' % err_msg)
130+
raise AFNIHeaderError('Failed to read variable from HEAD file '
131+
f'due to improper type casting. {err_msg}')
134132
else:
135133
# AFNI string attributes will always start with open single quote and
136134
# end with a tilde (NUL). These attributes CANNOT contain tildes (so

nibabel/casting.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -268,7 +268,7 @@ def type_info(np_type):
268268
# and then give up. At this stage we're expecting exotic longdouble or
269269
# their complex equivalent.
270270
if np_type not in (np.longdouble, np.longcomplex) or width not in (16, 32):
271-
raise FloatingError('We had not expected type %s' % np_type)
271+
raise FloatingError(f'We had not expected type {np_type}')
272272
if (vals == (1, 1, 16) and on_powerpc() and
273273
_check_maxexp(np.longdouble, 1024)):
274274
# double pair on PPC. The _check_nmant routine does not work for this
@@ -296,8 +296,7 @@ def type_info(np_type):
296296
maxexp=16384,
297297
width=width)
298298
else: # don't recognize the type
299-
raise FloatingError('We had not expected long double type %s '
300-
'with info %s' % (np_type, info))
299+
raise FloatingError(f'We had not expected long double type {np_type} with info {info}')
301300
return ret
302301

303302

@@ -402,7 +401,7 @@ def as_int(x, check=True):
402401
return ix
403402
fx = np.floor(x)
404403
if check and fx != x:
405-
raise FloatingError('Not an integer: %s' % x)
404+
raise FloatingError(f'Not an integer: {x}')
406405
if not fx.dtype.type == np.longdouble:
407406
return int(x)
408407
# Subtract float64 chunks until we have all of the number. If the int is

nibabel/cifti2/cifti2.py

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ class Cifti2HeaderError(Exception):
9292
def _value_if_klass(val, klass):
9393
if val is None or isinstance(val, klass):
9494
return val
95-
raise ValueError('Not a valid %s instance.' % klass.__name__)
95+
raise ValueError(f'Not a valid {klass.__name__} instance.')
9696

9797

9898
def _underscore(string):
@@ -291,8 +291,7 @@ def _to_xml_element(self):
291291
v = _float_01(getattr(self, c_))
292292
except ValueError:
293293
raise Cifti2HeaderError(
294-
'Label invalid %s needs to be a float between 0 and 1. '
295-
'and it is %s' % (c_, v)
294+
f'Label invalid {c_} needs to be a float between 0 and 1. and it is {v}'
296295
)
297296

298297
lab = xml.Element('Label')
@@ -1379,9 +1378,8 @@ def __init__(self,
13791378
self.update_headers()
13801379

13811380
if self._dataobj.shape != self.header.matrix.get_data_shape():
1382-
warn("Dataobj shape {} does not match shape expected from CIFTI-2 header {}".format(
1383-
self._dataobj.shape, self.header.matrix.get_data_shape()
1384-
))
1381+
warn(f"Dataobj shape {self._dataobj.shape} does not match shape "
1382+
f"expected from CIFTI-2 header {self.header.matrix.get_data_shape()}")
13851383

13861384
@property
13871385
def nifti_header(self):
@@ -1459,9 +1457,8 @@ def to_file_map(self, file_map=None):
14591457
header.extensions.append(extension)
14601458
if self._dataobj.shape != self.header.matrix.get_data_shape():
14611459
raise ValueError(
1462-
"Dataobj shape {} does not match shape expected from CIFTI-2 header {}".format(
1463-
self._dataobj.shape, self.header.matrix.get_data_shape()
1464-
))
1460+
f"Dataobj shape {self._dataobj.shape} does not match shape "
1461+
f"expected from CIFTI-2 header {self.header.matrix.get_data_shape()}")
14651462
# if intent code is not set, default to unknown CIFTI
14661463
if header.get_intent()[0] == 'none':
14671464
header.set_intent('NIFTI_INTENT_CONNECTIVITY_UNKNOWN')

0 commit comments

Comments
 (0)