Skip to content

Commit b183b73

Browse files
committed
More f-strings
flynt -ll 999 . All changes were reviewed manually
1 parent b10fbc1 commit b183b73

File tree

12 files changed

+41
-51
lines changed

12 files changed

+41
-51
lines changed

nibabel/_version.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,8 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
125125
root = os.path.dirname(root) # up a level
126126

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

132132

@@ -283,17 +283,17 @@ 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"] = (f"unable to parse git-describe output: '{describe_out}'")
286+
pieces["error"] = f"unable to parse git-describe output: '{describe_out}'"
287287
return pieces
288288

289289
# tag
290290
full_tag = mo.group(1)
291291
if not full_tag.startswith(tag_prefix):
292292
if verbose:
293-
fmt = "tag '%s' doesn't start with prefix '%s'"
294-
print(fmt % (full_tag, tag_prefix))
295-
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
296-
% (full_tag, tag_prefix))
293+
txt = f"tag '{full_tag}' doesn't start with prefix '{tag_prefix}'"
294+
print(txt)
295+
pieces["error"] = (f"tag '{full_tag}' doesn't start with prefix "
296+
f"'{tag_prefix}'")
297297
return pieces
298298
pieces["closest-tag"] = full_tag[len(tag_prefix):]
299299

nibabel/analyze.py

Lines changed: 3 additions & 5 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())

nibabel/arrayproxy.py

Lines changed: 4 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(f"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,8 @@ 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} "
416+
f"into shape {shape!s}")
417417
return self.__class__(file_like=self.file_like,
418418
spec=(shape, self._dtype, self._offset,
419419
self._slope, self._inter),

nibabel/benchmarks/bench_arrayproxy_slicing.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,8 @@ def fmt_sliceobj(sliceobj):
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... '
104+
f'({int(round(np.prod(SHAPE) * 4 / 1048576.0))} MB)')
105105

106106
data = np.array(np.random.random(SHAPE), dtype=np.float32)
107107

@@ -180,8 +180,8 @@ def testfunc():
180180
data[:, 2] = np.nan
181181
data[:, 3] = [r[5] - r[6] for r in results]
182182

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

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

nibabel/brikhead.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -114,8 +114,8 @@ def _unpack_var(var):
114114
TEMPLATE_SPACE ORIG
115115
"""
116116

117-
err_msg = ('Please check HEAD file to ensure it is AFNI compliant. '
118-
'Offending attribute:\n%s' % var)
117+
err_msg = (f'Please check HEAD file to ensure it is AFNI compliant. '
118+
f'Offending attribute:\n{var}')
119119
atype, aname = TYPE_RE.findall(var), NAME_RE.findall(var)
120120
if len(atype) != 1:
121121
raise AFNIHeaderError(f'Invalid attribute type entry in HEAD file. {err_msg}')
@@ -127,8 +127,8 @@ def _unpack_var(var):
127127
try:
128128
attr = [atype(f) for f in attr.split()]
129129
except ValueError:
130-
raise AFNIHeaderError('Failed to read variable from HEAD file due '
131-
'to improper type casting. %s' % err_msg)
130+
raise AFNIHeaderError(f'Failed to read variable from HEAD file '
131+
f'due to improper type casting. {err_msg}')
132132
else:
133133
# AFNI string attributes will always start with open single quote and
134134
# end with a tilde (NUL). These attributes CANNOT contain tildes (so

nibabel/casting.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -296,8 +296,8 @@ 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 '
300+
f'type {np_type} with info {info}')
301301
return ret
302302

303303

nibabel/cifti2/cifti2.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -291,8 +291,8 @@ 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 '
295+
f'float between 0 and 1. and it is {v}'
296296
)
297297

298298
lab = xml.Element('Label')
@@ -1379,9 +1379,8 @@ def __init__(self,
13791379
self.update_headers()
13801380

13811381
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-
))
1382+
warn(f"Dataobj shape {self._dataobj.shape} does not match shape "
1383+
f"expected from CIFTI-2 header {self.header.matrix.get_data_shape()}")
13851384

13861385
@property
13871386
def nifti_header(self):
@@ -1459,9 +1458,8 @@ def to_file_map(self, file_map=None):
14591458
header.extensions.append(extension)
14601459
if self._dataobj.shape != self.header.matrix.get_data_shape():
14611460
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-
))
1461+
f"Dataobj shape {self._dataobj.shape} does not match shape "
1462+
f"expected from CIFTI-2 header {self.header.matrix.get_data_shape()}")
14651463
# if intent code is not set, default to unknown CIFTI
14661464
if header.get_intent()[0] == 'none':
14671465
header.set_intent('NIFTI_INTENT_CONNECTIVITY_UNKNOWN')

nibabel/spatialimages.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -516,11 +516,11 @@ def __str__(self):
516516
shape = self.shape
517517
affine = self.affine
518518
return '\n'.join((str(self.__class__),
519-
'data shape %s' % (shape,),
519+
f'data shape {shape}',
520520
'affine: ',
521-
'%s' % affine,
521+
f'{affine}',
522522
'metadata:',
523-
'%s' % self._header))
523+
f'{self._header}'))
524524

525525
def get_data_dtype(self):
526526
return self._header.get_data_dtype()

nibabel/tests/test_volumeutils.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1224,9 +1224,8 @@ def read(self, n_bytes):
12241224
array_from_file(shape, np.int8, NoStringIO())
12251225
except IOError as err:
12261226
message = str(err)
1227-
assert message == 'Expected {0} bytes, got {1} bytes from {2}\n' \
1228-
' - could the file be damaged?'.format(
1229-
11390625000000000000, 0, 'object')
1227+
assert message == (f"Expected {11390625000000000000} bytes, got {0} "
1228+
f"bytes from {'object'}\n - could the file be damaged?")
12301229

12311230

12321231
def test__ftype4scaled_finite_warningfilters():

nibabel/volumeutils.py

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -526,11 +526,8 @@ def array_from_file(shape, in_dtype, infile, offset=0, order='F', mmap=True):
526526
n_read = len(data_bytes)
527527
needs_copy = True
528528
if n_bytes != n_read:
529-
raise IOError('Expected {0} bytes, got {1} bytes from {2}\n'
530-
' - could the file be damaged?'.format(
531-
n_bytes,
532-
n_read,
533-
getattr(infile, 'name', 'object')))
529+
raise IOError(f"Expected {n_bytes} bytes, got {n_read} bytes from "
530+
f"{getattr(infile, 'name', 'object')}\n - could the file be damaged?")
534531
arr = np.ndarray(shape, in_dtype, buffer=data_bytes, order=order)
535532
if needs_copy:
536533
return arr.copy()
@@ -747,10 +744,8 @@ def array_to_file(data, fileobj, out_dtype=None, offset=0,
747744
# nan_fill can be (just) outside clip range
748745
nan_fill = np.clip(nan_fill, both_mn, both_mx)
749746
else:
750-
raise ValueError("nan_fill == {0}, outside safe int range "
751-
"({1}-{2}); change scaling or "
752-
"set nan2zero=False?".format(
753-
nan_fill, int(both_mn), int(both_mx)))
747+
raise ValueError(f"nan_fill == {nan_fill}, outside safe int range "
748+
f"({int(both_mn)}-{int(both_mx)}); change scaling or set nan2zero=False?")
754749
# Make sure non-nan output clipped to shared range
755750
post_mn = np.max([post_mn, both_mn])
756751
post_mx = np.min([post_mx, both_mx])

0 commit comments

Comments
 (0)