Skip to content

Commit 6738d9a

Browse files
MNT: Apply pyupgrade suggestions
1 parent d33a05a commit 6738d9a

28 files changed

+54
-58
lines changed

doc/tools/apigen.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def __init__(self,
4242
module_skip_patterns=None,
4343
other_defines=True
4444
):
45-
""" Initialize package for parsing
45+
r""" Initialize package for parsing
4646
4747
Parameters
4848
----------
@@ -358,7 +358,7 @@ def _survives_exclude(self, matchstr, match_type):
358358
return True
359359

360360
def discover_modules(self):
361-
""" Return module sequence discovered from ``self.package_name``
361+
r""" Return module sequence discovered from ``self.package_name``
362362
363363
364364
Parameters

nibabel/arraywriters.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -438,8 +438,8 @@ def _range_scale(self, in_min, in_max):
438438
# not lose precision because min/max are of fp type.
439439
out_min, out_max = np.array((out_min, out_max), dtype=big_float)
440440
else: # (u)int
441-
out_min, out_max = [int_to_float(v, big_float)
442-
for v in (out_min, out_max)]
441+
out_min, out_max = (int_to_float(v, big_float)
442+
for v in (out_min, out_max))
443443
if self._out_dtype.kind == 'u':
444444
if in_min < 0 and in_max > 0:
445445
raise WriterError('Cannot scale negative and positive '
@@ -562,15 +562,15 @@ def to_fileobj(self, fileobj, order='F', nan2zero=None):
562562

563563
def _iu2iu(self):
564564
# (u)int to (u)int
565-
mn, mx = [as_int(v) for v in self.finite_range()]
565+
mn, mx = (as_int(v) for v in self.finite_range())
566566
# range may be greater than the largest integer for this type.
567567
# as_int needed to work round numpy 1.4.1 int casting bug
568568
out_dtype = self._out_dtype
569569
# Options in this method are scaling using intercept only. These will
570570
# have to pass through ``self.scaler_dtype`` (because the intercept is
571571
# in this type).
572-
o_min, o_max = [as_int(v)
573-
for v in shared_range(self.scaler_dtype, out_dtype)]
572+
o_min, o_max = (as_int(v)
573+
for v in shared_range(self.scaler_dtype, out_dtype))
574574
type_range = o_max - o_min
575575
mn2mx = mx - mn
576576
if mn2mx <= type_range: # might offset be enough?
@@ -619,8 +619,8 @@ def _range_scale(self, in_min, in_max):
619619
in_min, in_max = as_int(in_min), as_int(in_max)
620620
in_range = int_to_float(in_max - in_min, big_float)
621621
# Cast to float for later processing.
622-
in_min, in_max = [int_to_float(v, big_float)
623-
for v in (in_min, in_max)]
622+
in_min, in_max = (int_to_float(v, big_float)
623+
for v in (in_min, in_max))
624624
if out_dtype.kind == 'f':
625625
# Type range, these are also floats
626626
info = type_info(out_dtype)

nibabel/cifti2/cifti2.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -648,8 +648,8 @@ def __init__(self, name=None, voxel_indices_ijk=None, vertices=None):
648648
self.vertices = vertices if vertices is not None else []
649649
for val in self.vertices:
650650
if not isinstance(val, Cifti2Vertices):
651-
raise ValueError(('Cifti2Parcel vertices must be instances of '
652-
'Cifti2Vertices'))
651+
raise ValueError('Cifti2Parcel vertices must be instances of '
652+
'Cifti2Vertices')
653653

654654
@property
655655
def voxel_indices_ijk(self):

nibabel/cifti2/tests/test_axes.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,8 @@ def get_axes():
9393
yield get_parcels()
9494
yield get_scalar()
9595
yield get_label()
96-
for elem in get_brain_models():
97-
yield elem
98-
for elem in get_series():
99-
yield elem
96+
yield from get_brain_models()
97+
yield from get_series()
10098

10199

102100
def test_brain_models():

nibabel/cifti2/tests/test_cifti2io_header.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def test_read_nifti2():
5050
# Error trying to read a CIFTI-2 image from a NIfTI2-only image.
5151
filemap = ci.Cifti2Image.make_file_map()
5252
for k in filemap:
53-
filemap[k].fileobj = io.open(NIFTI2_DATA)
53+
filemap[k].fileobj = open(NIFTI2_DATA)
5454
with pytest.raises(ValueError):
5555
ci.Cifti2Image.from_file_map(filemap)
5656

nibabel/cmdline/diff.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ def get_data_diff(files, max_abs=0, max_rel=0, dtype=np.float64):
234234
# Since we operated on sub-selected values already, we need
235235
# to plug them back in
236236
candidates[
237-
tuple((indexes[sub_thr] for indexes in np.where(candidates)))
237+
tuple(indexes[sub_thr] for indexes in np.where(candidates))
238238
] = False
239239
max_rel_diff = np.max(rel_diff)
240240
else:

nibabel/cmdline/ls.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ def proc_file(f, opts):
145145
freq = np.bincount(inv)
146146
counts = " ".join("%g:%d" % (i, f) for i, f in zip(items, freq))
147147
row += ["@l" + counts]
148-
except IOError as e:
148+
except OSError as e:
149149
verbose(2, f"Failed to obtain stats/counts -- {e}")
150150
row += [_err()]
151151
return row

nibabel/cmdline/parrec2nii.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ def proc_file(infile, opts):
158158
else:
159159
outfilename = basefilename + '.nii'
160160
if os.path.isfile(outfilename) and not opts.overwrite:
161-
raise IOError(f'Output file "{outfilename}" exists, use --overwrite to overwrite it')
161+
raise OSError(f'Output file "{outfilename}" exists, use --overwrite to overwrite it')
162162

163163
# load the PAR header and data
164164
scaling = 'dv' if opts.scaling == 'off' else opts.scaling

nibabel/cmdline/roi.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def lossless_slice(img, slicers):
2121
def parse_slice(crop, allow_step=True):
2222
if crop is None:
2323
return slice(None)
24-
start, stop, *extra = [int(val) if val else None for val in crop.split(":")]
24+
start, stop, *extra = (int(val) if val else None for val in crop.split(":"))
2525
if len(extra) > 1:
2626
raise ValueError(f"Cannot parse specification: {crop}")
2727
if not allow_step and extra and extra[0] not in (1, None):

nibabel/ecat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,7 @@ def get_series_framenumbers(mlist):
471471
try:
472472
frame_dict[frame_stored] = trueframenumbers[true_order] + 1
473473
except IndexError:
474-
raise IOError('Error in header or mlist order unknown')
474+
raise OSError('Error in header or mlist order unknown')
475475
return frame_dict
476476

477477

nibabel/filebasedimages.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -430,7 +430,7 @@ def _sniff_meta_for(klass, filename, sniff_nbytes, sniff=None):
430430
try:
431431
with ImageOpener(meta_fname, 'rb') as fobj:
432432
binaryblock = fobj.read(sniff_nbytes)
433-
except (IOError, EOFError):
433+
except (OSError, EOFError):
434434
return None
435435
return (binaryblock, meta_fname)
436436

@@ -564,7 +564,7 @@ def from_stream(klass, io_obj: io.IOBase):
564564
return klass.from_file_map(klass._filemap_from_iobase(io_obj))
565565

566566
def to_stream(self, io_obj: io.IOBase, **kwargs):
567-
"""Save image to writable IO stream
567+
r"""Save image to writable IO stream
568568
569569
Parameters
570570
----------

nibabel/freesurfer/io.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def _read_volume_info(fobj):
6868
'zras', 'cras']:
6969
pair = fobj.readline().decode('utf-8').split('=')
7070
if pair[0].strip() != key or len(pair) != 2:
71-
raise IOError('Error parsing volume info.')
71+
raise OSError('Error parsing volume info.')
7272
if key in ('valid', 'filename'):
7373
volume_info[key] = pair[1].strip()
7474
elif key == 'volume':

nibabel/gifti/gifti.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ class GiftiNVPairs:
154154
'GiftiNVPairs objects are deprecated. Use the GiftiMetaData object '
155155
'as a dict, instead.',
156156
'4.0', '6.0')
157-
def __init__(self, name=u'', value=u''):
157+
def __init__(self, name='', value=''):
158158
self._name = name
159159
self._value = value
160160
self._container = None
@@ -480,7 +480,7 @@ def __init__(self,
480480
coordsys=None,
481481
ordering="C",
482482
meta=None,
483-
ext_fname=u'',
483+
ext_fname='',
484484
ext_offset=0):
485485
"""
486486
Returns a shell object that cannot be saved.
@@ -702,7 +702,7 @@ class GiftiImage(xml.XmlSerializable, SerializableImage):
702702
parser = None
703703

704704
def __init__(self, header=None, extra=None, file_map=None, meta=None,
705-
labeltable=None, darrays=None, version=u"1.0"):
705+
labeltable=None, darrays=None, version="1.0"):
706706
super(GiftiImage, self).__init__(header=header, extra=extra,
707707
file_map=file_map)
708708
if darrays is None:

nibabel/nicom/dicomreaders.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ def read_mosaic_dir(dicom_path,
8383
gradients = []
8484
arrays = []
8585
if len(filenames) == 0:
86-
raise IOError(f'Found no files with "{full_globber}"')
86+
raise OSError(f'Found no files with "{full_globber}"')
8787
for fname in filenames:
8888
dcm_w = wrapper_from_file(fname, **dicom_kwargs)
8989
# Because the routine sorts by filename, it only makes sense to use

nibabel/nicom/tests/test_dicomreaders.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def test_read_dwis():
3030
assert_array_almost_equal(aff, EXPECTED_AFFINE)
3131
assert_array_almost_equal(bs, (0, EXPECTED_PARAMS[0]))
3232
assert_array_almost_equal(gs, (np.zeros((3,)), EXPECTED_PARAMS[1]))
33-
with pytest.raises(IOError):
33+
with pytest.raises(OSError):
3434
didr.read_mosaic_dwi_dir('improbable')
3535

3636

nibabel/nifti1.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2269,7 +2269,7 @@ def load(filename):
22692269
------
22702270
ImageFileError
22712271
if `filename` doesn't look like NIfTI1;
2272-
IOError
2272+
OSError
22732273
if `filename` does not exist.
22742274
"""
22752275
try:

nibabel/nifti2.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -265,7 +265,7 @@ def load(filename):
265265
------
266266
ImageFileError
267267
if `filename` doesn't look like nifti2;
268-
IOError
268+
OSError
269269
if `filename` does not exist.
270270
"""
271271
try:

nibabel/spm99analyze.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -278,7 +278,7 @@ def from_file_map(klass, file_map, *, mmap=True, keep_file_open=None):
278278
file_map, mmap=mmap, keep_file_open=keep_file_open)
279279
try:
280280
matf = file_map['mat'].get_prepare_fileobj()
281-
except IOError:
281+
except OSError:
282282
return ret
283283
# Allow for possibility of empty file -> no update to affine
284284
with matf:

nibabel/streamlines/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def detect_format(fileobj):
5353
try:
5454
if format.is_correct_format(fileobj):
5555
return format
56-
except IOError:
56+
except OSError:
5757
pass
5858

5959
if isinstance(fileobj, str):

nibabel/streamlines/tests/test_array_sequence.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def test_deprecated_data_attribute(self):
101101
seq.data
102102

103103
def test_creating_arraysequence_from_generator(self):
104-
gen_1, gen_2 = itertools.tee((e for e in SEQ_DATA['data']))
104+
gen_1, gen_2 = itertools.tee(e for e in SEQ_DATA['data'])
105105
seq = ArraySequence(gen_1)
106106
seq_with_buffer = ArraySequence(gen_2, buffer_size=256)
107107

@@ -201,7 +201,7 @@ def test_arraysequence_extend(self):
201201

202202
# Extend with a generator.
203203
seq = SEQ_DATA['seq'].copy() # Copy because of in-place modification.
204-
seq.extend((d for d in new_data))
204+
seq.extend(d for d in new_data)
205205
check_arr_seq(seq, SEQ_DATA['data'] + new_data)
206206

207207
# Extend with another `ArraySequence` object.

nibabel/streamlines/trk.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -504,8 +504,8 @@ def save(self, fileobj):
504504
header['scalar_name'][:] = scalar_name
505505

506506
for t in tractogram:
507-
if any((len(d) != len(t.streamline)
508-
for d in t.data_for_points.values())):
507+
if any(len(d) != len(t.streamline)
508+
for d in t.data_for_points.values()):
509509
raise DataError("Missing scalars for some points!")
510510

511511
points = np.asarray(t.streamline)

nibabel/tests/test_arrayproxy.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -440,7 +440,7 @@ def _count_ImageOpeners(proxy, data, voxels):
440440
CountingImageOpener.num_openers = 0
441441
# expected data is defined in the test_keep_file_open_* tests
442442
for i in range(voxels.shape[0]):
443-
x, y, z = [int(c) for c in voxels[i, :]]
443+
x, y, z = (int(c) for c in voxels[i, :])
444444
assert proxy[x, y, z] == x * 100 + y * 10 + z
445445
return CountingImageOpener.num_openers
446446

nibabel/tests/test_casting.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def test_shared_range():
4545
if thresh_overflow:
4646
assert np.all((bit_bigger == casted_mx) | (bit_bigger == imax))
4747
else:
48-
assert np.all((bit_bigger <= casted_mx))
48+
assert np.all(bit_bigger <= casted_mx)
4949
if it in np.sctypes['uint']:
5050
assert mn == 0
5151
continue
@@ -71,7 +71,7 @@ def test_shared_range():
7171
if thresh_overflow:
7272
assert np.all((bit_smaller == casted_mn) | (bit_smaller == imin))
7373
else:
74-
assert np.all((bit_smaller >= casted_mn))
74+
assert np.all(bit_smaller >= casted_mn)
7575

7676

7777
def test_shared_range_inputs():

nibabel/tests/test_ecat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ def test_mlist_errors(self):
144144
neworder = [frames_order[x][0] for x in sorted(frames_order)]
145145
assert neworder == [1, 2, 3, 4, 5]
146146
with suppress_warnings():
147-
with pytest.raises(IOError):
147+
with pytest.raises(OSError):
148148
get_series_framenumbers(mlist)
149149

150150

nibabel/tests/test_funcs.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,8 @@ def test_concat():
4343

4444
affine = np.eye(4)
4545
for dim in range(2, 6):
46-
all_shapes_ND = tuple((shape[:dim] for shape in all_shapes_5D))
47-
all_shapes_N1D_unary = tuple((shape + (1,) for shape in all_shapes_ND))
46+
all_shapes_ND = tuple(shape[:dim] for shape in all_shapes_5D)
47+
all_shapes_N1D_unary = tuple(shape + (1,) for shape in all_shapes_ND)
4848
all_shapes = all_shapes_ND + all_shapes_N1D_unary
4949

5050
# Loop over all possible combinations of images, in first and

nibabel/tests/test_loadsave.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ def test_read_img_data_nifti():
139139
img.file_map = img.filespec_to_file_map(froot)
140140
# Trying to read from this filemap will generate an error because
141141
# we are going to read from files that do not exist
142-
with pytest.deprecated_call(), pytest.raises(IOError):
142+
with pytest.deprecated_call(), pytest.raises(OSError):
143143
read_img_data(img)
144144
img.to_file_map()
145145
# Load - now the scaling and offset correctly applied

nibabel/tests/test_volumeutils.py

+7-9
Original file line numberDiff line numberDiff line change
@@ -165,16 +165,14 @@ def test_array_from_file():
165165
arr = array_from_file((0,), np.dtype('f8'), BytesIO())
166166
assert len(arr) == 0
167167
# Check error from small file
168-
with pytest.raises(IOError):
168+
with pytest.raises(OSError):
169169
array_from_file(shape, dtype, BytesIO())
170170
# check on real file
171171
fd, fname = tempfile.mkstemp()
172172
with InTemporaryDirectory():
173173
open(fname, 'wb').write(b'1')
174174
in_buf = open(fname, 'rb')
175-
# For windows this will raise a WindowsError from mmap, Unices
176-
# appear to raise an IOError
177-
with pytest.raises(Exception):
175+
with pytest.raises(OSError):
178176
array_from_file(shape, dtype, in_buf)
179177
del in_buf
180178

@@ -983,7 +981,7 @@ def test_seek_tell():
983981
assert fobj.tell() == 10
984982
seek_tell(fobj, 10)
985983
assert fobj.tell() == 10
986-
with pytest.raises(IOError):
984+
with pytest.raises(OSError):
987985
seek_tell(fobj, 5)
988986
# Make sure read seeks don't affect file
989987
with ImageOpener(in_file, 'rb') as fobj:
@@ -1003,10 +1001,10 @@ def test_seek_tell_logic():
10031001
class BabyBio(BytesIO):
10041002

10051003
def seek(self, *args):
1006-
raise IOError()
1004+
raise OSError()
10071005
bio = BabyBio()
10081006
# Fresh fileobj, position 0, can't seek - error
1009-
with pytest.raises(IOError):
1007+
with pytest.raises(OSError):
10101008
bio.seek(10)
10111009
# Put fileobj in correct position by writing
10121010
ZEROB = b'\x00'
@@ -1015,7 +1013,7 @@ def seek(self, *args):
10151013
assert bio.tell() == 10
10161014
assert bio.getvalue() == ZEROB * 10
10171015
# Try write zeros to get to new position
1018-
with pytest.raises(IOError):
1016+
with pytest.raises(OSError):
10191017
bio.seek(20)
10201018
seek_tell(bio, 20, write0=True)
10211019
assert bio.getvalue() == ZEROB * 20
@@ -1206,7 +1204,7 @@ def read(self, n_bytes):
12061204
return b''
12071205
try:
12081206
array_from_file(shape, np.int8, NoStringIO())
1209-
except IOError as err:
1207+
except OSError as err:
12101208
message = str(err)
12111209
assert message == ("Expected 11390625000000000000 bytes, got 0 "
12121210
"bytes from object\n - could the file be damaged?")

0 commit comments

Comments
 (0)