Skip to content

MNT: Apply pyupgrade suggestions #1154

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 15, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions doc/tools/apigen.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def __init__(self,
module_skip_patterns=None,
other_defines=True
):
""" Initialize package for parsing
r""" Initialize package for parsing

Parameters
----------
Expand Down Expand Up @@ -358,7 +358,7 @@ def _survives_exclude(self, matchstr, match_type):
return True

def discover_modules(self):
""" Return module sequence discovered from ``self.package_name``
r""" Return module sequence discovered from ``self.package_name``


Parameters
Expand Down
4 changes: 2 additions & 2 deletions nibabel/cifti2/cifti2.py
Original file line number Diff line number Diff line change
Expand Up @@ -648,8 +648,8 @@ def __init__(self, name=None, voxel_indices_ijk=None, vertices=None):
self.vertices = vertices if vertices is not None else []
for val in self.vertices:
if not isinstance(val, Cifti2Vertices):
raise ValueError(('Cifti2Parcel vertices must be instances of '
'Cifti2Vertices'))
raise ValueError('Cifti2Parcel vertices must be instances of '
'Cifti2Vertices')

@property
def voxel_indices_ijk(self):
Expand Down
6 changes: 2 additions & 4 deletions nibabel/cifti2/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,10 +93,8 @@ def get_axes():
yield get_parcels()
yield get_scalar()
yield get_label()
for elem in get_brain_models():
yield elem
for elem in get_series():
yield elem
yield from get_brain_models()
yield from get_series()


def test_brain_models():
Expand Down
2 changes: 1 addition & 1 deletion nibabel/cifti2/tests/test_cifti2io_header.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def test_read_nifti2():
# Error trying to read a CIFTI-2 image from a NIfTI2-only image.
filemap = ci.Cifti2Image.make_file_map()
for k in filemap:
filemap[k].fileobj = io.open(NIFTI2_DATA)
filemap[k].fileobj = open(NIFTI2_DATA)
with pytest.raises(ValueError):
ci.Cifti2Image.from_file_map(filemap)

Expand Down
2 changes: 1 addition & 1 deletion nibabel/cmdline/ls.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def proc_file(f, opts):
freq = np.bincount(inv)
counts = " ".join("%g:%d" % (i, f) for i, f in zip(items, freq))
row += ["@l" + counts]
except IOError as e:
except OSError as e:
verbose(2, f"Failed to obtain stats/counts -- {e}")
row += [_err()]
return row
Expand Down
2 changes: 1 addition & 1 deletion nibabel/cmdline/parrec2nii.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def proc_file(infile, opts):
else:
outfilename = basefilename + '.nii'
if os.path.isfile(outfilename) and not opts.overwrite:
raise IOError(f'Output file "{outfilename}" exists, use --overwrite to overwrite it')
raise OSError(f'Output file "{outfilename}" exists, use --overwrite to overwrite it')

# load the PAR header and data
scaling = 'dv' if opts.scaling == 'off' else opts.scaling
Expand Down
2 changes: 1 addition & 1 deletion nibabel/ecat.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,7 @@ def get_series_framenumbers(mlist):
try:
frame_dict[frame_stored] = trueframenumbers[true_order] + 1
except IndexError:
raise IOError('Error in header or mlist order unknown')
raise OSError('Error in header or mlist order unknown')
return frame_dict


Expand Down
4 changes: 2 additions & 2 deletions nibabel/filebasedimages.py
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ def _sniff_meta_for(klass, filename, sniff_nbytes, sniff=None):
try:
with ImageOpener(meta_fname, 'rb') as fobj:
binaryblock = fobj.read(sniff_nbytes)
except (IOError, EOFError):
except (OSError, EOFError):
return None
return (binaryblock, meta_fname)

Expand Down Expand Up @@ -564,7 +564,7 @@ def from_stream(klass, io_obj: io.IOBase):
return klass.from_file_map(klass._filemap_from_iobase(io_obj))

def to_stream(self, io_obj: io.IOBase, **kwargs):
"""Save image to writable IO stream
r"""Save image to writable IO stream

Parameters
----------
Expand Down
2 changes: 1 addition & 1 deletion nibabel/freesurfer/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def _read_volume_info(fobj):
'zras', 'cras']:
pair = fobj.readline().decode('utf-8').split('=')
if pair[0].strip() != key or len(pair) != 2:
raise IOError('Error parsing volume info.')
raise OSError('Error parsing volume info.')
if key in ('valid', 'filename'):
volume_info[key] = pair[1].strip()
elif key == 'volume':
Expand Down
6 changes: 3 additions & 3 deletions nibabel/gifti/gifti.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ class GiftiNVPairs:
'GiftiNVPairs objects are deprecated. Use the GiftiMetaData object '
'as a dict, instead.',
'4.0', '6.0')
def __init__(self, name=u'', value=u''):
def __init__(self, name='', value=''):
self._name = name
self._value = value
self._container = None
Expand Down Expand Up @@ -480,7 +480,7 @@ def __init__(self,
coordsys=None,
ordering="C",
meta=None,
ext_fname=u'',
ext_fname='',
ext_offset=0):
"""
Returns a shell object that cannot be saved.
Expand Down Expand Up @@ -702,7 +702,7 @@ class GiftiImage(xml.XmlSerializable, SerializableImage):
parser = None

def __init__(self, header=None, extra=None, file_map=None, meta=None,
labeltable=None, darrays=None, version=u"1.0"):
labeltable=None, darrays=None, version="1.0"):
super(GiftiImage, self).__init__(header=header, extra=extra,
file_map=file_map)
if darrays is None:
Expand Down
2 changes: 1 addition & 1 deletion nibabel/nicom/dicomreaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def read_mosaic_dir(dicom_path,
gradients = []
arrays = []
if len(filenames) == 0:
raise IOError(f'Found no files with "{full_globber}"')
raise OSError(f'Found no files with "{full_globber}"')
for fname in filenames:
dcm_w = wrapper_from_file(fname, **dicom_kwargs)
# Because the routine sorts by filename, it only makes sense to use
Expand Down
2 changes: 1 addition & 1 deletion nibabel/nicom/tests/test_dicomreaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def test_read_dwis():
assert_array_almost_equal(aff, EXPECTED_AFFINE)
assert_array_almost_equal(bs, (0, EXPECTED_PARAMS[0]))
assert_array_almost_equal(gs, (np.zeros((3,)), EXPECTED_PARAMS[1]))
with pytest.raises(IOError):
with pytest.raises(OSError):
didr.read_mosaic_dwi_dir('improbable')


Expand Down
2 changes: 1 addition & 1 deletion nibabel/nifti1.py
Original file line number Diff line number Diff line change
Expand Up @@ -2269,7 +2269,7 @@ def load(filename):
------
ImageFileError
if `filename` doesn't look like NIfTI1;
IOError
OSError
if `filename` does not exist.
"""
try:
Expand Down
2 changes: 1 addition & 1 deletion nibabel/nifti2.py
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ def load(filename):
------
ImageFileError
if `filename` doesn't look like nifti2;
IOError
OSError
if `filename` does not exist.
"""
try:
Expand Down
2 changes: 1 addition & 1 deletion nibabel/spm99analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ def from_file_map(klass, file_map, *, mmap=True, keep_file_open=None):
file_map, mmap=mmap, keep_file_open=keep_file_open)
try:
matf = file_map['mat'].get_prepare_fileobj()
except IOError:
except OSError:
return ret
# Allow for possibility of empty file -> no update to affine
with matf:
Expand Down
2 changes: 1 addition & 1 deletion nibabel/streamlines/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def detect_format(fileobj):
try:
if format.is_correct_format(fileobj):
return format
except IOError:
except OSError:
pass

if isinstance(fileobj, str):
Expand Down
2 changes: 1 addition & 1 deletion nibabel/tests/test_arrayproxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ def _count_ImageOpeners(proxy, data, voxels):
CountingImageOpener.num_openers = 0
# expected data is defined in the test_keep_file_open_* tests
for i in range(voxels.shape[0]):
x, y, z = [int(c) for c in voxels[i, :]]
x, y, z = (int(c) for c in voxels[i, :])
assert proxy[x, y, z] == x * 100 + y * 10 + z
return CountingImageOpener.num_openers

Expand Down
2 changes: 1 addition & 1 deletion nibabel/tests/test_ecat.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def test_mlist_errors(self):
neworder = [frames_order[x][0] for x in sorted(frames_order)]
assert neworder == [1, 2, 3, 4, 5]
with suppress_warnings():
with pytest.raises(IOError):
with pytest.raises(OSError):
get_series_framenumbers(mlist)


Expand Down
2 changes: 1 addition & 1 deletion nibabel/tests/test_loadsave.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def test_read_img_data_nifti():
img.file_map = img.filespec_to_file_map(froot)
# Trying to read from this filemap will generate an error because
# we are going to read from files that do not exist
with pytest.deprecated_call(), pytest.raises(IOError):
with pytest.deprecated_call(), pytest.raises(OSError):
read_img_data(img)
img.to_file_map()
# Load - now the scaling and offset correctly applied
Expand Down
16 changes: 7 additions & 9 deletions nibabel/tests/test_volumeutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,16 +165,14 @@ def test_array_from_file():
arr = array_from_file((0,), np.dtype('f8'), BytesIO())
assert len(arr) == 0
# Check error from small file
with pytest.raises(IOError):
with pytest.raises(OSError):
array_from_file(shape, dtype, BytesIO())
# check on real file
fd, fname = tempfile.mkstemp()
with InTemporaryDirectory():
open(fname, 'wb').write(b'1')
in_buf = open(fname, 'rb')
# For windows this will raise a WindowsError from mmap, Unices
# appear to raise an IOError
with pytest.raises(Exception):
with pytest.raises(OSError):
array_from_file(shape, dtype, in_buf)
del in_buf

Expand Down Expand Up @@ -983,7 +981,7 @@ def test_seek_tell():
assert fobj.tell() == 10
seek_tell(fobj, 10)
assert fobj.tell() == 10
with pytest.raises(IOError):
with pytest.raises(OSError):
seek_tell(fobj, 5)
# Make sure read seeks don't affect file
with ImageOpener(in_file, 'rb') as fobj:
Expand All @@ -1003,10 +1001,10 @@ def test_seek_tell_logic():
class BabyBio(BytesIO):

def seek(self, *args):
raise IOError()
raise OSError()
bio = BabyBio()
# Fresh fileobj, position 0, can't seek - error
with pytest.raises(IOError):
with pytest.raises(OSError):
bio.seek(10)
# Put fileobj in correct position by writing
ZEROB = b'\x00'
Expand All @@ -1015,7 +1013,7 @@ def seek(self, *args):
assert bio.tell() == 10
assert bio.getvalue() == ZEROB * 10
# Try write zeros to get to new position
with pytest.raises(IOError):
with pytest.raises(OSError):
bio.seek(20)
seek_tell(bio, 20, write0=True)
assert bio.getvalue() == ZEROB * 20
Expand Down Expand Up @@ -1206,7 +1204,7 @@ def read(self, n_bytes):
return b''
try:
array_from_file(shape, np.int8, NoStringIO())
except IOError as err:
except OSError as err:
message = str(err)
assert message == ("Expected 11390625000000000000 bytes, got 0 "
"bytes from object\n - could the file be damaged?")
Expand Down
10 changes: 5 additions & 5 deletions nibabel/volumeutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,7 @@ def array_from_file(shape, in_dtype, infile, offset=0, order='F', mmap=True):
n_read = len(data_bytes)
needs_copy = True
if n_bytes != n_read:
raise IOError(f"Expected {n_bytes} bytes, got {n_read} bytes from "
raise OSError(f"Expected {n_bytes} bytes, got {n_read} bytes from "
f"{getattr(infile, 'name', 'object')}\n - could the file be damaged?")
arr = np.ndarray(shape, in_dtype, buffer=data_bytes, order=order)
if needs_copy:
Expand Down Expand Up @@ -822,7 +822,7 @@ def seek_tell(fileobj, offset, write0=False):
Parameters
----------
fileobj : file-like
object implementing ``seek`` and (if seek raises an IOError) ``tell``
object implementing ``seek`` and (if seek raises an OSError) ``tell``
offset : int
position in file to which to seek
write0 : {False, True}, optional
Expand All @@ -832,16 +832,16 @@ def seek_tell(fileobj, offset, write0=False):
"""
try:
fileobj.seek(offset)
except IOError as e:
except OSError as e:
# This can be a negative seek in write mode for gz file object or any
# seek in write mode for a bz2 file object
pos = fileobj.tell()
if pos == offset:
return
if not write0:
raise IOError(str(e))
raise OSError(str(e))
if pos > offset:
raise IOError("Can't write to seek backwards")
raise OSError("Can't write to seek backwards")
fileobj.write(b'\x00' * (offset - pos))
assert fileobj.tell() == offset

Expand Down