Skip to content

Commit 5aca3f2

Browse files
authored
Merge pull request #1405 from effigies/chore/ruff
chore: Update ruff, address complaints
2 parents f81f5a7 + eaa7200 commit 5aca3f2

36 files changed

+82
-87
lines changed

.git-blame-ignore-revs

+4
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
# Sun Jan 12 12:22:13 2025 -0500 - [email protected] - sty: ruff format [git-blame-ignore-rev]
2+
40e41208a0f04063b3c4e373a65da1a2a6a275b5
3+
# Sun Jan 12 11:51:49 2025 -0500 - [email protected] - STY: ruff format [git-blame-ignore-rev]
4+
7e5d584910c67851dcfcd074ff307122689b61f5
15
# Sun Jan 1 12:38:02 2023 -0500 - [email protected] - STY: Run pre-commit config on all files
26
d14c1cf282a9c3b19189f490f10c35f5739e24d1
37
# Thu Dec 29 22:53:17 2022 -0500 - [email protected] - STY: Reduce array().astype() and similar constructs

.pre-commit-config.yaml

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
exclude: ".*/data/.*"
22
repos:
33
- repo: https://github.com/pre-commit/pre-commit-hooks
4-
rev: v4.6.0
4+
rev: v5.0.0
55
hooks:
66
- id: trailing-whitespace
77
- id: end-of-file-fixer
@@ -13,7 +13,7 @@ repos:
1313
- id: check-merge-conflict
1414
- id: check-vcs-permalinks
1515
- repo: https://github.com/astral-sh/ruff-pre-commit
16-
rev: v0.6.4
16+
rev: v0.9.1
1717
hooks:
1818
- id: ruff
1919
args: [ --fix ]
@@ -24,7 +24,7 @@ repos:
2424
args: [ --select, ISC001, --fix ]
2525
exclude: = ["doc", "tools"]
2626
- repo: https://github.com/pre-commit/mirrors-mypy
27-
rev: v1.11.2
27+
rev: v1.14.1
2828
hooks:
2929
- id: mypy
3030
# Sync with project.optional-dependencies.typing

bin/parrec2nii

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
#!python
2-
"""PAR/REC to NIfTI converter
3-
"""
2+
"""PAR/REC to NIfTI converter"""
43

54
from nibabel.cmdline.parrec2nii import main
65

nibabel/benchmarks/bench_array_to_file.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -29,24 +29,25 @@ def bench_array_to_file():
2929
sys.stdout.flush()
3030
print_git_title('\nArray to file')
3131
mtime = measure('array_to_file(arr, BytesIO(), np.float32)', repeat)
32-
print('%30s %6.2f' % ('Save float64 to float32', mtime))
32+
fmt = '{:30s} {:6.2f}'.format
33+
print(fmt('Save float64 to float32', mtime))
3334
mtime = measure('array_to_file(arr, BytesIO(), np.int16)', repeat)
34-
print('%30s %6.2f' % ('Save float64 to int16', mtime))
35+
print(fmt('Save float64 to int16', mtime))
3536
# Set a lot of NaNs to check timing
3637
arr[:, :, :, 1] = np.nan
3738
mtime = measure('array_to_file(arr, BytesIO(), np.float32)', repeat)
38-
print('%30s %6.2f' % ('Save float64 to float32, NaNs', mtime))
39+
print(fmt('Save float64 to float32, NaNs', mtime))
3940
mtime = measure('array_to_file(arr, BytesIO(), np.int16)', repeat)
40-
print('%30s %6.2f' % ('Save float64 to int16, NaNs', mtime))
41+
print(fmt('Save float64 to int16, NaNs', mtime))
4142
# Set a lot of infs to check timing
4243
arr[:, :, :, 1] = np.inf
4344
mtime = measure('array_to_file(arr, BytesIO(), np.float32)', repeat)
44-
print('%30s %6.2f' % ('Save float64 to float32, infs', mtime))
45+
print(fmt('Save float64 to float32, infs', mtime))
4546
mtime = measure('array_to_file(arr, BytesIO(), np.int16)', repeat)
46-
print('%30s %6.2f' % ('Save float64 to int16, infs', mtime))
47+
print(fmt('Save float64 to int16, infs', mtime))
4748
# Int16 input, float output
4849
arr = np.random.random_integers(low=-1000, high=1000, size=img_shape)
4950
arr = arr.astype(np.int16)
5051
mtime = measure('array_to_file(arr, BytesIO(), np.float32)', repeat)
51-
print('%30s %6.2f' % ('Save Int16 to float32', mtime))
52+
print(fmt('Save Int16 to float32', mtime))
5253
sys.stdout.flush()

nibabel/benchmarks/bench_arrayproxy_slicing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ def fmt_sliceobj(sliceobj):
9696
slcstr.append(s)
9797
else:
9898
slcstr.append(str(int(s * SHAPE[i])))
99-
return f"[{', '.join(slcstr)}]"
99+
return f'[{", ".join(slcstr)}]'
100100

101101
with InTemporaryDirectory():
102102
print(f'Generating test data... ({int(round(np.prod(SHAPE) * 4 / 1048576.0))} MB)')

nibabel/benchmarks/bench_finite_range.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,17 @@ def bench_finite_range():
2828
sys.stdout.flush()
2929
print_git_title('\nFinite range')
3030
mtime = measure('finite_range(arr)', repeat)
31-
print('%30s %6.2f' % ('float64 all finite', mtime))
31+
fmt = '{:30s} {:6.2f}'.format
32+
print(fmt('float64 all finite', mtime))
3233
arr[:, :, :, 1] = np.nan
3334
mtime = measure('finite_range(arr)', repeat)
34-
print('%30s %6.2f' % ('float64 many NaNs', mtime))
35+
print(fmt('float64 many NaNs', mtime))
3536
arr[:, :, :, 1] = np.inf
3637
mtime = measure('finite_range(arr)', repeat)
37-
print('%30s %6.2f' % ('float64 many infs', mtime))
38+
print(fmt('float64 many infs', mtime))
3839
# Int16 input, float output
3940
arr = np.random.random_integers(low=-1000, high=1000, size=img_shape)
4041
arr = arr.astype(np.int16)
4142
mtime = measure('finite_range(arr)', repeat)
42-
print('%30s %6.2f' % ('int16', mtime))
43+
print(fmt('int16', mtime))
4344
sys.stdout.flush()

nibabel/benchmarks/bench_load_save.py

+8-7
Original file line numberDiff line numberDiff line change
@@ -34,20 +34,21 @@ def bench_load_save():
3434
print_git_title('Image load save')
3535
hdr.set_data_dtype(np.float32)
3636
mtime = measure('sio.truncate(0); img.to_file_map()', repeat)
37-
print('%30s %6.2f' % ('Save float64 to float32', mtime))
37+
fmt = '{:30s} {:6.2f}'.format
38+
print(fmt('Save float64 to float32', mtime))
3839
mtime = measure('img.from_file_map(img.file_map)', repeat)
39-
print('%30s %6.2f' % ('Load from float32', mtime))
40+
print(fmt('Load from float32', mtime))
4041
hdr.set_data_dtype(np.int16)
4142
mtime = measure('sio.truncate(0); img.to_file_map()', repeat)
42-
print('%30s %6.2f' % ('Save float64 to int16', mtime))
43+
print(fmt('Save float64 to int16', mtime))
4344
mtime = measure('img.from_file_map(img.file_map)', repeat)
44-
print('%30s %6.2f' % ('Load from int16', mtime))
45+
print(fmt('Load from int16', mtime))
4546
# Set a lot of NaNs to check timing
4647
arr[:, :, :20] = np.nan
4748
mtime = measure('sio.truncate(0); img.to_file_map()', repeat)
48-
print('%30s %6.2f' % ('Save float64 to int16, NaNs', mtime))
49+
print(fmt('Save float64 to int16, NaNs', mtime))
4950
mtime = measure('img.from_file_map(img.file_map)', repeat)
50-
print('%30s %6.2f' % ('Load from int16, NaNs', mtime))
51+
print(fmt('Load from int16, NaNs', mtime))
5152
# Int16 input, float output
5253
arr = np.random.random_integers(low=-1000, high=1000, size=img_shape)
5354
arr = arr.astype(np.int16)
@@ -57,5 +58,5 @@ def bench_load_save():
5758
hdr = img.header
5859
hdr.set_data_dtype(np.float32)
5960
mtime = measure('sio.truncate(0); img.to_file_map()', repeat)
60-
print('%30s %6.2f' % ('Save Int16 to float32', mtime))
61+
print(fmt('Save Int16 to float32', mtime))
6162
sys.stdout.flush()

nibabel/benchmarks/butils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@
55

66
def print_git_title(title):
77
"""Prints title string with git hash if possible, and underline"""
8-
title = f"{title} for git revision {get_info()['commit_hash']}"
8+
title = f'{title} for git revision {get_info()["commit_hash"]}'
99
print(title)
1010
print('-' * len(title))

nibabel/brikhead.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -555,7 +555,7 @@ def filespec_to_file_map(klass, filespec):
555555
fname = fholder.filename
556556
if key == 'header' and not os.path.exists(fname):
557557
for ext in klass._compressed_suffixes:
558-
fname = fname[: -len(ext)] if fname.endswith(ext) else fname
558+
fname = fname.removesuffix(ext)
559559
elif key == 'image' and not os.path.exists(fname):
560560
for ext in klass._compressed_suffixes:
561561
if os.path.exists(fname + ext):

nibabel/cifti2/cifti2.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -294,8 +294,7 @@ def __setitem__(self, key, value):
294294
self._labels[key] = Cifti2Label(*([key] + list(value)))
295295
except ValueError:
296296
raise ValueError(
297-
'Key should be int, value should be sequence '
298-
'of str and 4 floats between 0 and 1'
297+
'Key should be int, value should be sequence of str and 4 floats between 0 and 1'
299298
)
300299

301300
def __delitem__(self, key):

nibabel/cifti2/cifti2_axes.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -634,8 +634,10 @@ def __eq__(self, other):
634634
return (
635635
(
636636
self.affine is None
637-
or np.allclose(self.affine, other.affine)
638-
and self.volume_shape == other.volume_shape
637+
or (
638+
np.allclose(self.affine, other.affine)
639+
and self.volume_shape == other.volume_shape
640+
)
639641
)
640642
and self.nvertices == other.nvertices
641643
and np.array_equal(self.name, other.name)

nibabel/cifti2/parse_cifti2.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -384,8 +384,7 @@ def StartElementHandler(self, name, attrs):
384384
model = self.struct_state[-1]
385385
if not isinstance(model, Cifti2BrainModel):
386386
raise Cifti2HeaderError(
387-
'VertexIndices element can only be a child '
388-
'of the CIFTI-2 BrainModel element'
387+
'VertexIndices element can only be a child of the CIFTI-2 BrainModel element'
389388
)
390389
self.fsm_state.append('VertexIndices')
391390
model.vertex_indices = index

nibabel/cmdline/dicomfs.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,7 @@ def main(args=None):
231231

232232
if opts.verbose:
233233
logger.addHandler(logging.StreamHandler(sys.stdout))
234-
logger.setLevel(opts.verbose > 1 and logging.DEBUG or logging.INFO)
234+
logger.setLevel(logging.DEBUG if opts.verbose > 1 else logging.INFO)
235235

236236
if len(files) != 2:
237237
sys.stderr.write(f'Please provide two arguments:\n{parser.usage}\n')

nibabel/cmdline/ls.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -103,8 +103,8 @@ def proc_file(f, opts):
103103

104104
row += [
105105
str(safe_get(h, 'data_dtype')),
106-
f"@l[{ap(safe_get(h, 'data_shape'), '%3g')}]",
107-
f"@l{ap(safe_get(h, 'zooms'), '%.2f', 'x')}",
106+
f'@l[{ap(safe_get(h, "data_shape"), "%3g")}]',
107+
f'@l{ap(safe_get(h, "zooms"), "%.2f", "x")}',
108108
]
109109
# Slope
110110
if (

nibabel/cmdline/tests/test_conform.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ def test_nondefault(tmpdir):
4747
voxel_size = (1, 2, 4)
4848
orientation = 'LAS'
4949
args = (
50-
f"{infile} {outfile} --out-shape {' '.join(map(str, out_shape))} "
51-
f"--voxel-size {' '.join(map(str, voxel_size))} --orientation {orientation}"
50+
f'{infile} {outfile} --out-shape {" ".join(map(str, out_shape))} '
51+
f'--voxel-size {" ".join(map(str, voxel_size))} --orientation {orientation}'
5252
)
5353
main(args.split())
5454
assert outfile.isfile()

nibabel/cmdline/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ def table2string(table, out=None):
5555
# eat whole entry while computing width for @w (for wide)
5656
markup_strip = re.compile('^@([lrc]|w.*)')
5757
col_width = [max(len(markup_strip.sub('', x)) for x in column) for column in zip(*table)]
58-
trans = str.maketrans("lrcw", "<>^^")
58+
trans = str.maketrans('lrcw', '<>^^')
5959
lines = []
6060
for row in table:
6161
line = []

nibabel/data.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ def make_datasource(pkg_def, **kwargs):
290290
pkg_hint = pkg_def.get('install hint', DEFAULT_INSTALL_HINT)
291291
msg = f'{e}; Is it possible you have not installed a data package?'
292292
if 'name' in pkg_def:
293-
msg += f"\n\nYou may need the package \"{pkg_def['name']}\""
293+
msg += f'\n\nYou may need the package "{pkg_def["name"]}"'
294294
if pkg_hint is not None:
295295
msg += f'\n\n{pkg_hint}'
296296
raise DataError(msg)

nibabel/deprecator.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ def __call__(
212212
messages.append('* deprecated from version: ' + since)
213213
if until:
214214
messages.append(
215-
f"* {'Raises' if self.is_bad_version(until) else 'Will raise'} "
215+
f'* {"Raises" if self.is_bad_version(until) else "Will raise"} '
216216
f'{exception} as of version: {until}'
217217
)
218218
message = '\n'.join(messages)

nibabel/filename_parser.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,7 @@ def types_filenames(
111111
template_fname = _stringify_path(template_fname)
112112
if not isinstance(template_fname, str):
113113
raise TypesFilenamesError('Need file name as input to set_filenames')
114-
if template_fname.endswith('.'):
115-
template_fname = template_fname[:-1]
114+
template_fname = template_fname.removesuffix('.')
116115
filename, found_ext, ignored, guessed_name = parse_filename(
117116
template_fname, types_exts, trailing_suffixes, match_case
118117
)

nibabel/gifti/tests/test_parse_gifti_fast.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -177,9 +177,9 @@ def assert_default_types(loaded):
177177
continue
178178
with suppress_warnings():
179179
loadedtype = type(getattr(loaded, attr))
180-
assert (
181-
loadedtype == defaulttype
182-
), f'Type mismatch for attribute: {attr} ({loadedtype} != {defaulttype})'
180+
assert loadedtype == defaulttype, (
181+
f'Type mismatch for attribute: {attr} ({loadedtype} != {defaulttype})'
182+
)
183183

184184

185185
def test_default_types():

nibabel/nifti1.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1804,7 +1804,7 @@ def set_slice_times(self, slice_times):
18041804
raise HeaderDataError(f'slice ordering of {st_order} fits with no known scheme')
18051805
if len(matching_labels) > 1:
18061806
warnings.warn(
1807-
f"Multiple slice orders satisfy: {', '.join(matching_labels)}. "
1807+
f'Multiple slice orders satisfy: {", ".join(matching_labels)}. '
18081808
'Choosing the first one'
18091809
)
18101810
label = matching_labels[0]

nibabel/parrec.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -782,10 +782,10 @@ def as_analyze_map(self):
782782
# Here we set the parameters we can to simplify PAR/REC
783783
# to NIfTI conversion.
784784
descr = (
785-
f"{self.general_info['exam_name']};"
786-
f"{self.general_info['patient_name']};"
787-
f"{self.general_info['exam_date'].replace(' ', '')};"
788-
f"{self.general_info['protocol_name']}"
785+
f'{self.general_info["exam_name"]};'
786+
f'{self.general_info["patient_name"]};'
787+
f'{self.general_info["exam_date"].replace(" ", "")};'
788+
f'{self.general_info["protocol_name"]}'
789789
)[:80]
790790
is_fmri = self.general_info['max_dynamics'] > 1
791791
# PAR/REC uses msec, but in _calc_zooms we convert to sec

nibabel/pointset.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ def to_mask(self, shape=None) -> SpatialImage:
178178
class GridIndices:
179179
"""Class for generating indices just-in-time"""
180180

181-
__slots__ = ('gridshape', 'dtype', 'shape')
181+
__slots__ = ('dtype', 'gridshape', 'shape')
182182
ndim = 2
183183

184184
def __init__(self, shape, dtype=None):

nibabel/rstutils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def rst_table(
5252
cross = format_chars.pop('cross', '+')
5353
title_heading = format_chars.pop('title_heading', '*')
5454
if len(format_chars) != 0:
55-
raise ValueError(f"Unexpected ``format_char`` keys {', '.join(format_chars)}")
55+
raise ValueError(f'Unexpected ``format_char`` keys {", ".join(format_chars)}')
5656
down_joiner = ' ' + down + ' '
5757
down_starter = down + ' '
5858
down_ender = ' ' + down

nibabel/streamlines/__init__.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -125,8 +125,7 @@ def save(tractogram, filename, **kwargs):
125125
tractogram_file = tractogram
126126
if tractogram_file_class is None or not isinstance(tractogram_file, tractogram_file_class):
127127
msg = (
128-
'The extension you specified is unusual for the provided'
129-
" 'TractogramFile' object."
128+
"The extension you specified is unusual for the provided 'TractogramFile' object."
130129
)
131130
warnings.warn(msg, ExtensionWarning)
132131

nibabel/streamlines/array_sequence.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def fn_binary_op(self, value):
8787
'__xor__',
8888
):
8989
_wrap(cls, op=op, inplace=False)
90-
_wrap(cls, op=f"__i{op.strip('_')}__", inplace=True)
90+
_wrap(cls, op=f'__i{op.strip("_")}__', inplace=True)
9191

9292
for op in ('__eq__', '__ne__', '__lt__', '__le__', '__gt__', '__ge__'):
9393
_wrap(cls, op)

nibabel/streamlines/tests/test_array_sequence.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -397,7 +397,7 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False):
397397
if op in CMP_OPS:
398398
continue
399399

400-
op = f"__i{op.strip('_')}__"
400+
op = f'__i{op.strip("_")}__'
401401
_test_binary(op, seq, SCALARS, ARRSEQS, inplace=True)
402402

403403
if op == '__itruediv__':

nibabel/streamlines/trk.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -579,7 +579,7 @@ def _read_header(fileobj):
579579
header_rec = header_rec.view(header_rec.dtype.newbyteorder())
580580
if header_rec['hdr_size'] != TrkFile.HEADER_SIZE:
581581
msg = (
582-
f"Invalid hdr_size: {header_rec['hdr_size']} "
582+
f'Invalid hdr_size: {header_rec["hdr_size"]} '
583583
f'instead of {TrkFile.HEADER_SIZE}'
584584
)
585585
raise HeaderError(msg)

nibabel/tests/data/check_parrec_reslice.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def gmean_norm(data):
6060
normal_data = normal_img.get_fdata()
6161
normal_normed = gmean_norm(normal_data)
6262

63-
print(f'RMS of standard image {normal_fname:<44}: {np.sqrt(np.sum(normal_normed ** 2))}')
63+
print(f'RMS of standard image {normal_fname:<44}: {np.sqrt(np.sum(normal_normed**2))}')
6464

6565
for parfile in glob.glob('*.PAR'):
6666
if parfile == normal_fname:
@@ -69,4 +69,4 @@ def gmean_norm(data):
6969
fixed_img = resample_img2img(normal_img, funny_img)
7070
fixed_data = fixed_img.get_fdata()
7171
difference_data = normal_normed - gmean_norm(fixed_data)
72-
print(f'RMS resliced {parfile:<52} : {np.sqrt(np.sum(difference_data ** 2))}')
72+
print(f'RMS resliced {parfile:<52} : {np.sqrt(np.sum(difference_data**2))}')

nibabel/tests/test_funcs.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -101,9 +101,9 @@ def test_concat():
101101
except ValueError as ve:
102102
assert expect_error, str(ve)
103103
else:
104-
assert (
105-
not expect_error
106-
), 'Expected a concatenation error, but got none.'
104+
assert not expect_error, (
105+
'Expected a concatenation error, but got none.'
106+
)
107107
assert_array_equal(all_imgs.get_fdata(), all_data)
108108
assert_array_equal(all_imgs.affine, affine)
109109

@@ -117,9 +117,9 @@ def test_concat():
117117
except ValueError as ve:
118118
assert expect_error, str(ve)
119119
else:
120-
assert (
121-
not expect_error
122-
), 'Expected a concatenation error, but got none.'
120+
assert not expect_error, (
121+
'Expected a concatenation error, but got none.'
122+
)
123123
assert_array_equal(all_imgs.get_fdata(), all_data)
124124
assert_array_equal(all_imgs.affine, affine)
125125

0 commit comments

Comments
 (0)