From 5529d857fef033f87de4a62283908dee7c6e1593 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Mon, 12 Dec 2022 21:29:34 +0100 Subject: [PATCH] MNT: Apply pyupgrade suggestions --- doc/tools/apigen.py | 4 ++-- nibabel/cifti2/cifti2.py | 4 ++-- nibabel/cifti2/tests/test_axes.py | 6 ++---- nibabel/cifti2/tests/test_cifti2io_header.py | 2 +- nibabel/cmdline/ls.py | 2 +- nibabel/cmdline/parrec2nii.py | 2 +- nibabel/ecat.py | 2 +- nibabel/filebasedimages.py | 4 ++-- nibabel/freesurfer/io.py | 2 +- nibabel/gifti/gifti.py | 6 +++--- nibabel/nicom/dicomreaders.py | 2 +- nibabel/nicom/tests/test_dicomreaders.py | 2 +- nibabel/nifti1.py | 2 +- nibabel/nifti2.py | 2 +- nibabel/spm99analyze.py | 2 +- nibabel/streamlines/__init__.py | 2 +- nibabel/tests/test_arrayproxy.py | 2 +- nibabel/tests/test_ecat.py | 2 +- nibabel/tests/test_loadsave.py | 2 +- nibabel/tests/test_volumeutils.py | 16 +++++++--------- nibabel/volumeutils.py | 10 +++++----- 21 files changed, 37 insertions(+), 41 deletions(-) diff --git a/doc/tools/apigen.py b/doc/tools/apigen.py index cabbd319c5..68d8f68749 100644 --- a/doc/tools/apigen.py +++ b/doc/tools/apigen.py @@ -42,7 +42,7 @@ def __init__(self, module_skip_patterns=None, other_defines=True ): - """ Initialize package for parsing + r""" Initialize package for parsing Parameters ---------- @@ -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 diff --git a/nibabel/cifti2/cifti2.py b/nibabel/cifti2/cifti2.py index b75fd01db9..31d631bb5f 100644 --- a/nibabel/cifti2/cifti2.py +++ b/nibabel/cifti2/cifti2.py @@ -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): diff --git a/nibabel/cifti2/tests/test_axes.py b/nibabel/cifti2/tests/test_axes.py index 3f6cb3a1a4..21cd83e80e 100644 --- a/nibabel/cifti2/tests/test_axes.py +++ b/nibabel/cifti2/tests/test_axes.py @@ -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(): diff --git a/nibabel/cifti2/tests/test_cifti2io_header.py b/nibabel/cifti2/tests/test_cifti2io_header.py index c4e0682af4..541ceaa30c 100644 --- a/nibabel/cifti2/tests/test_cifti2io_header.py +++ b/nibabel/cifti2/tests/test_cifti2io_header.py @@ -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) diff --git a/nibabel/cmdline/ls.py b/nibabel/cmdline/ls.py index 91e55860f4..2995ff58c5 100755 --- a/nibabel/cmdline/ls.py +++ b/nibabel/cmdline/ls.py @@ -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 diff --git a/nibabel/cmdline/parrec2nii.py b/nibabel/cmdline/parrec2nii.py index bf8146e8f9..0f868bd06b 100644 --- a/nibabel/cmdline/parrec2nii.py +++ b/nibabel/cmdline/parrec2nii.py @@ -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 diff --git a/nibabel/ecat.py b/nibabel/ecat.py index f206e482de..1d7bddaa16 100644 --- a/nibabel/ecat.py +++ b/nibabel/ecat.py @@ -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 diff --git a/nibabel/filebasedimages.py b/nibabel/filebasedimages.py index 180fe7c6a7..5162263a28 100644 --- a/nibabel/filebasedimages.py +++ b/nibabel/filebasedimages.py @@ -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) @@ -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 ---------- diff --git a/nibabel/freesurfer/io.py b/nibabel/freesurfer/io.py index e2f48d88eb..77f7fe892a 100644 --- a/nibabel/freesurfer/io.py +++ b/nibabel/freesurfer/io.py @@ -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': diff --git a/nibabel/gifti/gifti.py b/nibabel/gifti/gifti.py index 6082d3739b..6fbc9245a7 100644 --- a/nibabel/gifti/gifti.py +++ b/nibabel/gifti/gifti.py @@ -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 @@ -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. @@ -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: diff --git a/nibabel/nicom/dicomreaders.py b/nibabel/nicom/dicomreaders.py index e4fbc625ab..56d7d56946 100644 --- a/nibabel/nicom/dicomreaders.py +++ b/nibabel/nicom/dicomreaders.py @@ -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 diff --git a/nibabel/nicom/tests/test_dicomreaders.py b/nibabel/nicom/tests/test_dicomreaders.py index 0ce7f8de2e..b1ae9edae9 100644 --- a/nibabel/nicom/tests/test_dicomreaders.py +++ b/nibabel/nicom/tests/test_dicomreaders.py @@ -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') diff --git a/nibabel/nifti1.py b/nibabel/nifti1.py index d434e50c32..1bffac10ce 100644 --- a/nibabel/nifti1.py +++ b/nibabel/nifti1.py @@ -2269,7 +2269,7 @@ def load(filename): ------ ImageFileError if `filename` doesn't look like NIfTI1; - IOError + OSError if `filename` does not exist. """ try: diff --git a/nibabel/nifti2.py b/nibabel/nifti2.py index 8c58569d96..10e789d076 100644 --- a/nibabel/nifti2.py +++ b/nibabel/nifti2.py @@ -265,7 +265,7 @@ def load(filename): ------ ImageFileError if `filename` doesn't look like nifti2; - IOError + OSError if `filename` does not exist. """ try: diff --git a/nibabel/spm99analyze.py b/nibabel/spm99analyze.py index 687a94da5a..b858a5efff 100644 --- a/nibabel/spm99analyze.py +++ b/nibabel/spm99analyze.py @@ -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: diff --git a/nibabel/streamlines/__init__.py b/nibabel/streamlines/__init__.py index 8dfe96f927..8767a2a48f 100644 --- a/nibabel/streamlines/__init__.py +++ b/nibabel/streamlines/__init__.py @@ -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): diff --git a/nibabel/tests/test_arrayproxy.py b/nibabel/tests/test_arrayproxy.py index 6857fdb1f7..eb296b516f 100644 --- a/nibabel/tests/test_arrayproxy.py +++ b/nibabel/tests/test_arrayproxy.py @@ -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 diff --git a/nibabel/tests/test_ecat.py b/nibabel/tests/test_ecat.py index 607345e473..3a48f204d3 100644 --- a/nibabel/tests/test_ecat.py +++ b/nibabel/tests/test_ecat.py @@ -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) diff --git a/nibabel/tests/test_loadsave.py b/nibabel/tests/test_loadsave.py index f2cf0242d5..c58b95d8e8 100644 --- a/nibabel/tests/test_loadsave.py +++ b/nibabel/tests/test_loadsave.py @@ -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 diff --git a/nibabel/tests/test_volumeutils.py b/nibabel/tests/test_volumeutils.py index 4994f94e48..6babe649fb 100644 --- a/nibabel/tests/test_volumeutils.py +++ b/nibabel/tests/test_volumeutils.py @@ -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 @@ -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: @@ -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' @@ -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 @@ -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?") diff --git a/nibabel/volumeutils.py b/nibabel/volumeutils.py index dc82287dbb..4e22c6ce29 100644 --- a/nibabel/volumeutils.py +++ b/nibabel/volumeutils.py @@ -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: @@ -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 @@ -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