Skip to content

Commit a3f51aa

Browse files
committed
STY: Use f-strings only where necessary
+ remove str calls in f-strings, one line if possible
1 parent 092dc9b commit a3f51aa

File tree

14 files changed

+33
-38
lines changed

14 files changed

+33
-38
lines changed

nibabel/cmdline/ls.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def proc_file(f, opts):
7373
h = vol.header
7474
except Exception as e:
7575
row += ['failed']
76-
verbose(2, f"Failed to gather information -- {str(e)}")
76+
verbose(2, f"Failed to gather information -- {e}")
7777
return row
7878

7979
row += [str(safe_get(h, 'data_dtype')),

nibabel/funcs.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -133,8 +133,7 @@ def concat_images(images, check_affines=True, axis=None):
133133
masked_shape = np.array(shape0)[idx_mask]
134134
for i, img in enumerate(images):
135135
if len(img.shape) != n_dim:
136-
raise ValueError(
137-
f'Image {i} has {len(img.shape)} dimensions, image 0 has {n_dim}')
136+
raise ValueError(f'Image {i} has {len(img.shape)} dimensions, image 0 has {n_dim}')
138137
if not np.all(np.array(img.shape)[idx_mask] == masked_shape):
139138
raise ValueError(f'shape {img.shape} for image {i} not compatible with '
140139
f'first image shape {shape0} with axis == {axis}')

nibabel/gifti/gifti.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -486,7 +486,7 @@ def to_xml_open(self):
486486
\tExternalFileOffset="%d">\n"""
487487
di = ""
488488
for i, n in enumerate(self.dims):
489-
di = di + f'\tDim{i}="{n}"\n'
489+
di = di + f'\tDim{i}="{n}\"\n'
490490
return out % (intent_codes.niistring[self.intent],
491491
data_type_codes.niistring[self.datatype],
492492
array_index_order_codes.label[self.ind_ord],

nibabel/parrec.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -429,8 +429,7 @@ def vol_is_full(slice_nos, slice_max, slice_min=1):
429429
"""
430430
slice_set = set(range(slice_min, slice_max + 1))
431431
if not slice_set.issuperset(slice_nos):
432-
raise ValueError(
433-
f'Slice numbers outside inclusive range {slice_min} to {slice_max}')
432+
raise ValueError(f'Slice numbers outside inclusive range {slice_min} to {slice_max}')
434433
vol_nos = np.array(vol_numbers(slice_nos))
435434
slice_nos = np.asarray(slice_nos)
436435
is_full = np.ones(slice_nos.shape, dtype=bool)

nibabel/streamlines/tck.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -211,14 +211,14 @@ def save(self, fileobj):
211211
data_for_streamline = first_item.data_for_streamline
212212
if len(data_for_streamline) > 0:
213213
keys = ", ".join(data_for_streamline.keys())
214-
msg = (f"TCK format does not support saving additional "
214+
msg = ("TCK format does not support saving additional "
215215
f"data alongside streamlines. Dropping: {keys}")
216216
warnings.warn(msg, DataWarning)
217217

218218
data_for_points = first_item.data_for_points
219219
if len(data_for_points) > 0:
220220
keys = ", ".join(data_for_points.keys())
221-
msg = (f"TCK format does not support saving additional "
221+
msg = ("TCK format does not support saving additional "
222222
f"data alongside points. Dropping: {keys}")
223223
warnings.warn(msg, DataWarning)
224224

@@ -330,13 +330,12 @@ def _read_header(fileobj):
330330
hdr['datatype'] = "Float32LE"
331331

332332
if not hdr['datatype'].startswith('Float32'):
333-
msg = (f"TCK only supports float32 dtype but 'datatype: "
333+
msg = ("TCK only supports float32 dtype but 'datatype: "
334334
f"{hdr['datatype']}' was specified in the header.")
335335
raise HeaderError(msg)
336336

337337
if 'file' not in hdr:
338-
msg = ("Missing 'file' attribute in TCK header."
339-
" Will try to guess it.")
338+
msg = "Missing 'file' attribute in TCK header. Will try to guess it."
340339
warnings.warn(msg, HeaderWarning)
341340
hdr['file'] = f'. {offset_data}'
342341

nibabel/streamlines/tractogram.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -108,9 +108,8 @@ def __setitem__(self, key, value):
108108
raise ValueError("data_per_streamline must be a 2D array.")
109109

110110
# We make sure there is the right amount of values
111-
if self.n_rows > 0 and len(value) != self.n_rows:
112-
msg = (f"The number of values ({len(value)}) should match "
113-
f"n_elements ({self.n_rows}).")
111+
if 0 < self.n_rows != len(value):
112+
msg = f"The number of values ({len(value)}) should match n_elements ({self.n_rows})."
114113
raise ValueError(msg)
115114

116115
self.store[key] = value
@@ -140,7 +139,7 @@ def extend(self, other):
140139
"""
141140
if (len(self) > 0 and len(other) > 0 and
142141
sorted(self.keys()) != sorted(other.keys())):
143-
msg = (f"Entry mismatched between the two PerArrayDict objects. "
142+
msg = ("Entry mismatched between the two PerArrayDict objects. "
144143
f"This PerArrayDict contains '{sorted(self.keys())}' "
145144
f"whereas the other contains '{sorted(other.keys())}'.")
146145
raise ValueError(msg)
@@ -364,7 +363,7 @@ def affine_to_rasmm(self, value):
364363
if value is not None:
365364
value = np.array(value)
366365
if value.shape != (4, 4):
367-
msg = (f"Affine matrix has a shape of (4, 4) but a ndarray with"
366+
msg = ("Affine matrix has a shape of (4, 4) but a ndarray with "
368367
f"shape {value.shape} was provided instead.")
369368
raise ValueError(msg)
370369

nibabel/streamlines/trk.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,7 @@ def encode_value_in_name(value, name, max_name_len=20):
160160
if len(encoded_name) > max_name_len:
161161
msg = (f"Data information named '{name}' is too long (need to be less"
162162
f" than {max_name_len - (len(str(value)) + 1)} characters "
163-
f"when storing more than one value for a given data information.")
163+
"when storing more than one value for a given data information.")
164164
raise ValueError(msg)
165165
# Fill to the end with zeros
166166
return encoded_name.ljust(max_name_len, '\x00').encode('latin1')
@@ -195,8 +195,8 @@ def decode_value_from_name(encoded_name):
195195
value = int(splits[1]) # Decode value.
196196
elif len(splits) > 2:
197197
# The remaining bytes are not \x00, raising.
198-
msg = (f"Wrong scalar_name or property_name: '{encoded_name}'."
199-
f" Unused characters should be \\x00.")
198+
msg = (f"Wrong scalar_name or property_name: '{encoded_name}'. "
199+
"Unused characters should be \\x00.")
200200
raise HeaderError(msg)
201201

202202
return name, value
@@ -473,8 +473,8 @@ def save(self, fileobj):
473473
data_for_streamline = first_item.data_for_streamline
474474
if len(data_for_streamline) > MAX_NB_NAMED_PROPERTIES_PER_STREAMLINE:
475475
msg = (f"Can only store {MAX_NB_NAMED_SCALARS_PER_POINT} named "
476-
f"data_per_streamline (also known as 'properties' in the "
477-
f"TRK format).")
476+
"data_per_streamline (also known as 'properties' in the "
477+
"TRK format).")
478478
raise ValueError(msg)
479479

480480
data_for_streamline_keys = sorted(data_for_streamline.keys())
@@ -491,8 +491,8 @@ def save(self, fileobj):
491491
data_for_points = first_item.data_for_points
492492
if len(data_for_points) > MAX_NB_NAMED_SCALARS_PER_POINT:
493493
msg = (f"Can only store {MAX_NB_NAMED_SCALARS_PER_POINT} "
494-
f"named data_per_point (also known as 'scalars' in "
495-
f"the TRK format).")
494+
"named data_per_point (also known as 'scalars' in "
495+
"the TRK format).")
496496
raise ValueError(msg)
497497

498498
data_for_points_keys = sorted(data_for_points.keys())
@@ -615,8 +615,8 @@ def _read_header(fileobj):
615615
# able to determine the axis directions.
616616
axcodes = aff2axcodes(header[Field.VOXEL_TO_RASMM])
617617
if None in axcodes:
618-
msg = (f"The 'vox_to_ras' affine is invalid! Could not"
619-
f" determine the axis directions from it.\n"
618+
msg = ("The 'vox_to_ras' affine is invalid! Could not"
619+
" determine the axis directions from it.\n"
620620
f"{header[Field.VOXEL_TO_RASMM]}")
621621
raise HeaderError(msg)
622622

nibabel/tests/test_deprecator.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ def test_dep_func(self):
9595
assert len(w) == 1
9696
assert (func.__doc__ ==
9797
f'foo\n\n* Will raise {ExpiredDeprecationError} '
98-
f'as of version: 99.4\n')
98+
'as of version: 99.4\n')
9999
func = dec('foo', until='1.8')(func_no_doc)
100100
with pytest.raises(ExpiredDeprecationError):
101101
func()
@@ -105,13 +105,13 @@ def test_dep_func(self):
105105
with pytest.raises(ExpiredDeprecationError):
106106
func()
107107
assert (func.__doc__ ==
108-
f'foo\n\n* deprecated from version: 1.2\n* Raises '
108+
'foo\n\n* deprecated from version: 1.2\n* Raises '
109109
f'{ExpiredDeprecationError} as of version: 1.8\n')
110110
func = dec('foo', '1.2', '1.8')(func_doc_long)
111111
assert (func.__doc__ ==
112-
f'A docstring\n \n foo\n \n * deprecated from version: 1.2\n '
112+
'A docstring\n \n foo\n \n * deprecated from version: 1.2\n '
113113
f'* Raises {ExpiredDeprecationError} as of version: 1.8\n \n'
114-
f' Some text\n')
114+
' Some text\n')
115115
with pytest.raises(ExpiredDeprecationError):
116116
func()
117117

nibabel/tests/test_image_types.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def check_img(img_path, img_klass, sniff_mode, sniff, expect_success,
9898
# Reuse the sniff... but it will only change for some
9999
# sniff_mode values.
100100
msg = (f'{expected_img_klass.__name__}/ {sniff_mode}/ '
101-
f'{str(expect_success)}')
101+
f'{expect_success}')
102102
sniff = check_img(img_path, klass, sniff_mode=sniff_mode,
103103
sniff=sniff, expect_success=expect_success,
104104
msg=msg)

nibabel/tests/test_nifti1.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ def test_magic_offset_checks(self):
266266
assert fhdr['vox_offset'] == bad_spm
267267
assert (message ==
268268
f'vox offset (={bad_spm:g}) not divisible by 16, '
269-
f'not SPM compatible; leaving at current value')
269+
'not SPM compatible; leaving at current value')
270270
# Check minimum offset (if offset set)
271271
hdr['magic'] = hdr.single_magic
272272
hdr['vox_offset'] = 10

0 commit comments

Comments
 (0)