Skip to content

Commit 5529d85

Browse files
MNT: Apply pyupgrade suggestions
1 parent d33a05a commit 5529d85

21 files changed

+37
-41
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/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/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/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/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_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_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?")

nibabel/volumeutils.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -465,7 +465,7 @@ def array_from_file(shape, in_dtype, infile, offset=0, order='F', mmap=True):
465465
n_read = len(data_bytes)
466466
needs_copy = True
467467
if n_bytes != n_read:
468-
raise IOError(f"Expected {n_bytes} bytes, got {n_read} bytes from "
468+
raise OSError(f"Expected {n_bytes} bytes, got {n_read} bytes from "
469469
f"{getattr(infile, 'name', 'object')}\n - could the file be damaged?")
470470
arr = np.ndarray(shape, in_dtype, buffer=data_bytes, order=order)
471471
if needs_copy:
@@ -822,7 +822,7 @@ def seek_tell(fileobj, offset, write0=False):
822822
Parameters
823823
----------
824824
fileobj : file-like
825-
object implementing ``seek`` and (if seek raises an IOError) ``tell``
825+
object implementing ``seek`` and (if seek raises an OSError) ``tell``
826826
offset : int
827827
position in file to which to seek
828828
write0 : {False, True}, optional
@@ -832,16 +832,16 @@ def seek_tell(fileobj, offset, write0=False):
832832
"""
833833
try:
834834
fileobj.seek(offset)
835-
except IOError as e:
835+
except OSError as e:
836836
# This can be a negative seek in write mode for gz file object or any
837837
# seek in write mode for a bz2 file object
838838
pos = fileobj.tell()
839839
if pos == offset:
840840
return
841841
if not write0:
842-
raise IOError(str(e))
842+
raise OSError(str(e))
843843
if pos > offset:
844-
raise IOError("Can't write to seek backwards")
844+
raise OSError("Can't write to seek backwards")
845845
fileobj.write(b'\x00' * (offset - pos))
846846
assert fileobj.tell() == offset
847847

0 commit comments

Comments
 (0)