Skip to content

Commit 2271c97

Browse files
committed
More f-strings
flynt -ll 999 . All changes were reviewed manually (Excluding versioneer)
1 parent b183b73 commit 2271c97

33 files changed

+158
-185
lines changed

nibabel/cifti2/cifti2_axes.py

Lines changed: 17 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -320,8 +320,8 @@ def __init__(self, name, voxel=None, vertex=None, affine=None,
320320
for check_name in ('name', 'voxel', 'vertex'):
321321
shape = (self.size, 3) if check_name == 'voxel' else (self.size, )
322322
if getattr(self, check_name).shape != shape:
323-
raise ValueError("Input {} has incorrect shape ({}) for BrainModelAxis axis".format(
324-
check_name, getattr(self, check_name).shape))
323+
raise ValueError(f"Input {check_name} has incorrect shape "
324+
f"({getattr(self, check_name).shape}) for BrainModelAxis axis")
325325

326326
@classmethod
327327
def from_mask(cls, mask, name='other', affine=None):
@@ -537,8 +537,8 @@ def to_cifti_brain_structure_name(name):
537537
else:
538538
proposed_name = f'CIFTI_STRUCTURE_{structure.upper()}_{orientation.upper()}'
539539
if proposed_name not in cifti2.CIFTI_BRAIN_STRUCTURES:
540-
raise ValueError('%s was interpreted as %s, which is not a valid CIFTI brain structure'
541-
% (name, proposed_name))
540+
raise ValueError(f'{name} was interpreted as {proposed_name}, which is not '
541+
f'a valid CIFTI brain structure')
542542
return proposed_name
543543

544544
@property
@@ -650,8 +650,8 @@ def __add__(self, other):
650650
nvertices = dict(self.nvertices)
651651
for name, value in other.nvertices.items():
652652
if name in nvertices.keys() and nvertices[name] != value:
653-
raise ValueError("Trying to concatenate two BrainModels with inconsistent "
654-
"number of vertices for %s" % name)
653+
raise ValueError(f"Trying to concatenate two BrainModels with "
654+
f"inconsistent number of vertices for {name}")
655655
nvertices[name] = value
656656
return self.__class__(
657657
np.append(self.name, other.name),
@@ -763,8 +763,8 @@ def __init__(self, name, voxels, vertices, affine=None, volume_shape=None, nvert
763763

764764
for check_name in ('name', 'voxels', 'vertices'):
765765
if getattr(self, check_name).shape != (self.size, ):
766-
raise ValueError("Input {} has incorrect shape ({}) for Parcel axis".format(
767-
check_name, getattr(self, check_name).shape))
766+
raise ValueError(f"Input {check_name} has incorrect shape "
767+
f"({getattr(self, check_name).shape}) for Parcel axis")
768768

769769
@classmethod
770770
def from_brain_models(cls, named_brain_models):
@@ -804,8 +804,8 @@ def from_brain_models(cls, named_brain_models):
804804
for name, _, bm_part in bm.iter_structures():
805805
if name in bm.nvertices.keys():
806806
if name in nvertices.keys() and nvertices[name] != bm.nvertices[name]:
807-
raise ValueError("Got multiple conflicting number of "
808-
"vertices for surface structure %s" % name)
807+
raise ValueError(f"Got multiple conflicting number of "
808+
f"vertices for surface structure {name}")
809809
nvertices[name] = bm.nvertices[name]
810810
vertices[name] = bm_part.vertex
811811
all_vertices[idx_parcel] = vertices
@@ -846,8 +846,7 @@ def from_index_mapping(cls, mim):
846846
name = vertex.brain_structure
847847
vertices[vertex.brain_structure] = np.array(vertex)
848848
if name not in nvertices.keys():
849-
raise ValueError("Number of vertices for surface structure %s not defined" %
850-
name)
849+
raise ValueError(f"Number of vertices for surface structure {name} not defined")
851850
all_voxels[idx_parcel] = voxels
852851
all_vertices[idx_parcel] = vertices
853852
all_names.append(parcel.name)
@@ -968,9 +967,8 @@ def __add__(self, other):
968967
nvertices = dict(self.nvertices)
969968
for name, value in other.nvertices.items():
970969
if name in nvertices.keys() and nvertices[name] != value:
971-
raise ValueError("Trying to concatenate two ParcelsAxis with inconsistent "
972-
"number of vertices for %s"
973-
% name)
970+
raise ValueError(f"Trying to concatenate two ParcelsAxis with "
971+
f"inconsistent number of vertices for {name}")
974972
nvertices[name] = value
975973
return self.__class__(
976974
np.append(self.name, other.name),
@@ -1042,8 +1040,8 @@ def __init__(self, name, meta=None):
10421040

10431041
for check_name in ('name', 'meta'):
10441042
if getattr(self, check_name).shape != (self.size, ):
1045-
raise ValueError("Input {} has incorrect shape ({}) for ScalarAxis axis".format(
1046-
check_name, getattr(self, check_name).shape))
1043+
raise ValueError(f"Input {check_name} has incorrect shape "
1044+
f"({getattr(self, check_name).shape}) for ScalarAxis axis")
10471045

10481046
@classmethod
10491047
def from_index_mapping(cls, mim):
@@ -1176,8 +1174,8 @@ def __init__(self, name, label, meta=None):
11761174

11771175
for check_name in ('name', 'meta', 'label'):
11781176
if getattr(self, check_name).shape != (self.size, ):
1179-
raise ValueError("Input {} has incorrect shape ({}) for LabelAxis axis".format(
1180-
check_name, getattr(self, check_name).shape))
1177+
raise ValueError(f"Input {check_name} has incorrect shape "
1178+
f"({getattr(self, check_name).shape}) for LabelAxis axis")
11811179

11821180
@classmethod
11831181
def from_index_mapping(cls, mim):

nibabel/cmdline/dicomfs.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -196,8 +196,8 @@ def release(self, path, flags, fh):
196196
def get_opt_parser():
197197
# use module docstring for help output
198198
p = OptionParser(
199-
usage="%s [OPTIONS] <DIRECTORY CONTAINING DICOMSs> <mount point>"
200-
% os.path.basename(sys.argv[0]),
199+
usage=f"{os.path.basename(sys.argv[0])} [OPTIONS] "
200+
f"<DIRECTORY CONTAINING DICOMSs> <mount point>",
201201
version="%prog " + nib.__version__)
202202

203203
p.add_options([

nibabel/cmdline/parrec2nii.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -158,8 +158,8 @@ def proc_file(infile, opts):
158158
else:
159159
outfilename = basefilename + '.nii'
160160
if os.path.isfile(outfilename) and not opts.overwrite:
161-
raise IOError('Output file "%s" exists, use --overwrite to '
162-
'overwrite it' % outfilename)
161+
raise IOError(f'Output file "{outfilename}" exists, '
162+
f'use --overwrite to overwrite it')
163163

164164
# load the PAR header and data
165165
scaling = 'dv' if opts.scaling == 'off' else opts.scaling
@@ -295,8 +295,8 @@ def proc_file(infile, opts):
295295
except MRIError:
296296
verbose('No EPI factors, dwell time not written')
297297
else:
298-
verbose('Writing dwell time (%r sec) calculated assuming %sT '
299-
'magnet' % (dwell_time, opts.field_strength))
298+
verbose(f'Writing dwell time ({dwell_time!r} sec) '
299+
f'calculated assuming {opts.field_strength}T magnet')
300300
with open(basefilename + '.dwell_time', 'w') as fid:
301301
fid.write(f'{dwell_time!r}\n')
302302
# done

nibabel/cmdline/tck2trk.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,9 @@ def main():
4141
filename, _ = os.path.splitext(tractogram)
4242
output_filename = filename + '.trk'
4343
if os.path.isfile(output_filename) and not args.force:
44-
msg = "Skipping existing file: '{}'. Use -f to overwrite."
45-
print(msg.format(output_filename))
44+
msg = (f"Skipping existing file: '{output_filename}'. "
45+
f"Use -f to overwrite.")
46+
print(msg)
4647
continue
4748

4849
# Build header using infos from the anatomical image.

nibabel/cmdline/tests/test_conform.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,8 @@ def test_nondefault(tmpdir):
4646
out_shape = (100, 100, 150)
4747
voxel_size = (1, 2, 4)
4848
orientation = "LAS"
49-
args = "{} {} --out-shape {} --voxel-size {} --orientation {}".format(
50-
infile, outfile, " ".join(map(str, out_shape)), " ".join(map(str, voxel_size)), orientation)
49+
args = (f"{infile} {outfile} --out-shape {' '.join(map(str, out_shape))} "
50+
f"--voxel-size {' '.join(map(str, voxel_size))} --orientation {orientation}")
5151
main(args.split())
5252
assert outfile.isfile()
5353
c = nib.load(outfile)

nibabel/cmdline/trk2tck.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,9 @@ def main():
3131
filename, _ = os.path.splitext(tractogram)
3232
output_filename = filename + '.tck'
3333
if os.path.isfile(output_filename) and not args.force:
34-
msg = "Skipping existing file: '{}'. Use -f to overwrite."
35-
print(msg.format(output_filename))
34+
msg = (f"Skipping existing file: '{output_filename}'. "
35+
f"Use -f to overwrite.")
36+
print(msg)
3637
continue
3738

3839
trk = nib.streamlines.load(tractogram)

nibabel/data.py

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -240,9 +240,8 @@ def find_data_dir(root_dirs, *names):
240240
pth = pjoin(path, ds_relative)
241241
if os.path.isdir(pth):
242242
return pth
243-
raise DataError('Could not find datasource "%s" in data path "%s"' %
244-
(ds_relative,
245-
os.path.pathsep.join(root_dirs)))
243+
raise DataError(f'Could not find datasource "{ds_relative}" in '
244+
f'data path "{os.path.pathsep.join(root_dirs)}"')
246245

247246

248247
def make_datasource(pkg_def, **kwargs):
@@ -313,9 +312,8 @@ def __init__(self, name, msg):
313312
def __getattr__(self, attr_name):
314313
""" Raise informative error accessing not-found attributes """
315314
raise BomberError(
316-
'Trying to access attribute "%s" '
317-
'of non-existent data "%s"\n\n%s\n' %
318-
(attr_name, self.name, self.msg))
315+
f'Trying to access attribute "{attr_name}" of '
316+
f'non-existent data "{self.name}"\n\n{self.msg}\n')
319317

320318

321319
def datasource_or_bomber(pkg_def, **options):
@@ -358,10 +356,6 @@ def datasource_or_bomber(pkg_def, **options):
358356
pkg_name = pkg_def['name']
359357
else:
360358
pkg_name = 'data at ' + unix_relpath
361-
msg = ('%(name)s is version %(pkg_version)s but we need '
362-
'version >= %(req_version)s\n\n%(pkg_hint)s' %
363-
dict(name=pkg_name,
364-
pkg_version=ds.version,
365-
req_version=version,
366-
pkg_hint=pkg_hint))
359+
msg = (f"{pkg_name} is version {ds.version} but we need "
360+
f"version >= {version}\n\n{pkg_hint}")
367361
return Bomber(sys_relpath, DataError(msg))

nibabel/deprecator.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -146,10 +146,8 @@ def __call__(self, message, since='', until='',
146146
if since:
147147
messages.append('* deprecated from version: ' + since)
148148
if until:
149-
messages.append('* {0} {1} as of version: {2}'.format(
150-
"Raises" if self.is_bad_version(until) else "Will raise",
151-
error_class,
152-
until))
149+
messages.append(f"* {'Raises' if self.is_bad_version(until) else 'Will raise'} "
150+
f"{error_class} as of version: {until}")
153151
message = '\n'.join(messages)
154152

155153
def deprecator(func):

nibabel/ecat.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -425,10 +425,8 @@ def get_frame_order(mlist):
425425
valid_order = np.argsort(ids)
426426
if not all(valid_order == sorted(valid_order)):
427427
# raise UserWarning if Frames stored out of order
428-
warnings.warn_explicit('Frames stored out of order;'
429-
'true order = %s\n'
430-
'frames will be accessed in order '
431-
'STORED, NOT true order' % valid_order,
428+
warnings.warn_explicit(f'Frames stored out of order;true order = {valid_order}\n'
429+
f'frames will be accessed in order STORED, NOT true order',
432430
UserWarning, 'ecat', 0)
433431
id_dict = {}
434432
for i in range(n_valid):

nibabel/filebasedimages.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ def from_header(klass, header=None):
3434
# different field names
3535
if type(header) == klass:
3636
return header.copy()
37-
raise NotImplementedError("Header class requires a conversion"
38-
" from %s to %s" % (klass, type(header)))
37+
raise NotImplementedError(f"Header class requires a conversion "
38+
f"from {klass} to {type(header)}")
3939

4040
@classmethod
4141
def from_fileobj(klass, fileobj):

0 commit comments

Comments
 (0)