Skip to content

Commit

Permalink
MNT: run ruff --fix
Browse files Browse the repository at this point in the history
Also fix remaining issues manually.
  • Loading branch information
DimitriPapadopoulos committed Dec 26, 2023
1 parent be32cd9 commit 90f5d3b
Show file tree
Hide file tree
Showing 55 changed files with 67 additions and 106 deletions.
4 changes: 2 additions & 2 deletions doc/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@

# Check for external Sphinx extensions we depend on
try:
import numpydoc
import numpydoc # noqa: F401
except ImportError:
raise RuntimeError('Need to install "numpydoc" package for doc build')
try:
import texext
import texext # noqa: F401
except ImportError:
raise RuntimeError('Need to install "texext" package for doc build')

Expand Down
1 change: 0 additions & 1 deletion doc/tools/apigen.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,6 @@ def discover_modules(self):

def write_modules_api(self, modules, outdir):
# upper-level modules
main_module = modules[0].split('.')[0]
ulms = [
'.'.join(m.split('.')[:2]) if m.count('.') >= 1 else m.split('.')[0] for m in modules
]
Expand Down
2 changes: 1 addition & 1 deletion doc/tools/build_modref_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def abort(error):

try:
__import__(package)
except ImportError as e:
except ImportError:
abort('Can not import ' + package)

module = sys.modules[package]
Expand Down
6 changes: 3 additions & 3 deletions nibabel/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##

# ruff: noqa: F401

import os

from .info import long_description as __doc__
Expand Down Expand Up @@ -39,12 +41,10 @@

# module imports
from . import analyze as ana
from . import ecat, imagestats, mriutils
from . import ecat, imagestats, mriutils, orientations, streamlines, viewers
from . import nifti1 as ni1
from . import orientations
from . import spm2analyze as spm2
from . import spm99analyze as spm99
from . import streamlines, viewers

# isort: split

Expand Down
1 change: 1 addition & 0 deletions nibabel/cifti2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
# copyright and license terms.
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
# ruff: noqa: F401
"""CIFTI-2 format IO
.. currentmodule:: nibabel.cifti2
Expand Down
2 changes: 1 addition & 1 deletion nibabel/cifti2/tests/test_cifti2.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import pytest

from nibabel import cifti2 as ci
from nibabel.cifti2.cifti2 import Cifti2HeaderError, _float_01, _value_if_klass
from nibabel.cifti2.cifti2 import _float_01, _value_if_klass
from nibabel.nifti2 import Nifti2Header
from nibabel.tests.test_dataobj_images import TestDataobjAPI as _TDA
from nibabel.tests.test_image_api import DtypeOverrideMixin, SerializeMixin
Expand Down
3 changes: 1 addition & 2 deletions nibabel/cifti2/tests/test_cifti2io_header.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##

import io
from os.path import dirname
from os.path import join as pjoin

Expand Down Expand Up @@ -38,7 +37,7 @@


def test_space_separated_affine():
img = ci.Cifti2Image.from_filename(pjoin(NIBABEL_TEST_DATA, 'row_major.dconn.nii'))
_ = ci.Cifti2Image.from_filename(pjoin(NIBABEL_TEST_DATA, 'row_major.dconn.nii'))


def test_read_nifti2():
Expand Down
2 changes: 1 addition & 1 deletion nibabel/cmdline/tests/test_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def test_convert_imgtype(tmp_path, ext, img_class):

def test_convert_nifti_int_fail(tmp_path):
infile = get_test_data(fname='anatomical.nii')
outfile = tmp_path / f'output.nii'
outfile = tmp_path / 'output.nii'

orig = nib.load(infile)
assert not outfile.exists()
Expand Down
3 changes: 1 addition & 2 deletions nibabel/cmdline/tests/test_roi.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import os
import unittest
from unittest import mock

import numpy as np
Expand Down Expand Up @@ -140,7 +139,7 @@ def test_entrypoint(capsys):
# Check that we handle missing args as expected
with mock.patch('sys.argv', ['nib-roi', '--help']):
try:
retval = main()
main()
except SystemExit:
pass
else:
Expand Down
2 changes: 0 additions & 2 deletions nibabel/cmdline/tests/test_stats.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##

import sys
from io import StringIO

import numpy as np

Expand Down
12 changes: 10 additions & 2 deletions nibabel/cmdline/tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,16 @@
import pytest

import nibabel as nib
from nibabel.cmdline.diff import *
from nibabel.cmdline.utils import *
from nibabel.cmdline.diff import (
ap,
display_diff,
get_data_diff,
get_data_hash_diff,
get_headers_diff,
main,
safe_get,
table2string,
)
from nibabel.testing import data_path


Expand Down
2 changes: 1 addition & 1 deletion nibabel/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

# Ignore warning requesting help with nicom
with pytest.warns(UserWarning):
import nibabel.nicom
pass


@pytest.fixture(scope='session', autouse=True)
Expand Down
2 changes: 2 additions & 0 deletions nibabel/freesurfer/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Reading functions for freesurfer files
"""

# ruff: noqa: F401

from .io import (
read_annot,
read_geometry,
Expand Down
2 changes: 2 additions & 0 deletions nibabel/gifti/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
gifti
"""

# ruff: noqa: F401

from .gifti import (
GiftiCoordSystem,
GiftiDataArray,
Expand Down
15 changes: 7 additions & 8 deletions nibabel/gifti/tests/test_gifti.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@
"""
import itertools
import sys
import warnings
from io import BytesIO

import numpy as np
import pytest
from numpy.testing import assert_array_almost_equal, assert_array_equal
from numpy.testing import assert_array_equal

from nibabel.tmpdirs import InTemporaryDirectory

Expand Down Expand Up @@ -312,7 +311,7 @@ def test_metadata_list_interface():
assert md['foo'] == 'bar'

# Append new NVPair
with pytest.warns(DeprecationWarning) as w:
with pytest.warns(DeprecationWarning) as _:
nvpair = GiftiNVPairs('key', 'value')
mdlist.append(nvpair)
assert len(mdlist) == 2
Expand All @@ -327,15 +326,15 @@ def test_metadata_list_interface():
assert len(md) == 0

# Extension adds multiple keys
with pytest.warns(DeprecationWarning) as w:
with pytest.warns(DeprecationWarning) as _:
foobar = GiftiNVPairs('foo', 'bar')
mdlist.extend([nvpair, foobar])
assert len(mdlist) == 2
assert len(md) == 2
assert md == {'key': 'value', 'foo': 'bar'}

# Insertion updates list order, though we don't attempt to preserve it in the dict
with pytest.warns(DeprecationWarning) as w:
with pytest.warns(DeprecationWarning) as _:
lastone = GiftiNVPairs('last', 'one')
mdlist.insert(1, lastone)
assert len(mdlist) == 3
Expand All @@ -358,14 +357,14 @@ def test_metadata_list_interface():
mypair.value = 'strings'
assert 'completelynew' not in md
assert md == {'foo': 'bar', 'last': 'one'}
# Check popping from the end (lastone inserted before foobar)
lastpair = mdlist.pop()
# Check popping from the end (last one inserted before foobar)
_ = mdlist.pop()
assert len(mdlist) == 1
assert len(md) == 1
assert md == {'last': 'one'}

# And let's remove an old pair with a new object
with pytest.warns(DeprecationWarning) as w:
with pytest.warns(DeprecationWarning) as _:
lastoneagain = GiftiNVPairs('last', 'one')
mdlist.remove(lastoneagain)
assert len(mdlist) == 0
Expand Down
4 changes: 2 additions & 2 deletions nibabel/gifti/tests/test_parse_gifti_fast.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,13 +433,13 @@ def test_external_file_failure_cases():
shutil.copy(DATA_FILE7, '.')
filename = pjoin(tmpdir, basename(DATA_FILE7))
with pytest.raises(GiftiParseError):
img = load(filename)
_ = load(filename)
# load from in-memory xml string (parser requires it as bytes)
with open(DATA_FILE7, 'rb') as f:
xmldata = f.read()
parser = GiftiImageParser()
with pytest.raises(GiftiParseError):
img = parser.parse(xmldata)
_ = parser.parse(xmldata)


def test_load_compressed():
Expand Down
1 change: 0 additions & 1 deletion nibabel/nicom/tests/test_ascconv.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from os.path import dirname
from os.path import join as pjoin

import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal

from .. import ascconv
Expand Down
1 change: 0 additions & 1 deletion nibabel/nicom/tests/test_csareader.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""Testing Siemens CSA header reader
"""
import gzip
import sys
from copy import deepcopy
from os.path import join as pjoin

Expand Down
2 changes: 1 addition & 1 deletion nibabel/nicom/tests/test_dicomwrappers.py
Original file line number Diff line number Diff line change
Expand Up @@ -626,7 +626,7 @@ def test_image_position(self):
def test_affine(self):
# Make sure we find orientation/position/spacing info
dw = didw.wrapper_from_file(DATA_FILE_4D)
aff = dw.affine
_ = dw.affine

@dicom_test
@pytest.mark.xfail(reason='Not packaged in install', raises=FileNotFoundError)
Expand Down
4 changes: 1 addition & 3 deletions nibabel/streamlines/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@
import os
import warnings

from .array_sequence import ArraySequence
from .header import Field
from .tck import TckFile
from .tractogram import LazyTractogram, Tractogram
from .tractogram import Tractogram
from .tractogram_file import ExtensionWarning
from .trk import TrkFile

Expand Down
3 changes: 1 addition & 2 deletions nibabel/streamlines/tests/test_array_sequence.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import itertools
import os
import sys
import tempfile
import unittest

Expand Down Expand Up @@ -220,7 +219,7 @@ def test_arraysequence_extend(self):
seq.extend(data)

# Extend after extracting some slice
working_slice = seq[:2]
_ = seq[:2]
seq.extend(ArraySequence(new_data))

def test_arraysequence_getitem(self):
Expand Down
1 change: 0 additions & 1 deletion nibabel/streamlines/tests/test_streamlines.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import os
import tempfile
import unittest
import warnings
from io import BytesIO
Expand Down
3 changes: 1 addition & 2 deletions nibabel/streamlines/tests/test_tck.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from numpy.testing import assert_array_equal

from ...testing import data_path, error_warnings
from .. import tck as tck_module
from ..array_sequence import ArraySequence
from ..tck import TckFile
from ..tractogram import Tractogram
Expand Down Expand Up @@ -138,7 +137,7 @@ def test_load_file_with_wrong_information(self):

# Simulate a TCK file with no `file` field.
new_tck_file = tck_file.replace(b'\nfile: . 67', b'')
with pytest.warns(HeaderWarning, match="Missing 'file'") as w:
with pytest.warns(HeaderWarning, match="Missing 'file'") as _:
tck = TckFile.load(BytesIO(new_tck_file))
assert_array_equal(tck.header['file'], '. 56')

Expand Down
1 change: 0 additions & 1 deletion nibabel/streamlines/tests/test_tractogram.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import copy
import operator
import sys
import unittest
import warnings
from collections import defaultdict
Expand Down
2 changes: 1 addition & 1 deletion nibabel/streamlines/tests/test_trk.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def test_load_file_with_wrong_information(self):
# Simulate a TRK where `vox_to_ras` is invalid.
trk_struct, trk_bytes = self.trk_with_bytes()
trk_struct[Field.VOXEL_TO_RASMM] = np.diag([0, 0, 0, 1])
with clear_and_catch_warnings(record=True, modules=[trk_module]) as w:
with clear_and_catch_warnings(record=True, modules=[trk_module]) as _:
with pytest.raises(HeaderError):
TrkFile.load(BytesIO(trk_bytes))

Expand Down
3 changes: 3 additions & 0 deletions nibabel/testing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
#
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
"""Utilities for testing"""

# ruff: noqa: F401

from __future__ import annotations

import os
Expand Down
3 changes: 1 addition & 2 deletions nibabel/tests/nibabel_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@

import unittest
from os import environ, listdir
from os.path import dirname, exists, isdir
from os.path import dirname, exists, isdir, realpath
from os.path import join as pjoin
from os.path import realpath


def get_nibabel_data():
Expand Down
3 changes: 1 addition & 2 deletions nibabel/tests/scriptrunner.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,8 @@
"""
import os
import sys
from os.path import dirname, isdir, isfile
from os.path import dirname, isdir, isfile, pathsep, realpath
from os.path import join as pjoin
from os.path import pathsep, realpath
from subprocess import PIPE, Popen

MY_PACKAGE = __package__
Expand Down
2 changes: 1 addition & 1 deletion nibabel/tests/test_affines.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def test_rescale_affine():
orig_shape = rng.randint(low=20, high=512, size=(3,))
orig_aff = np.eye(4)
orig_aff[:3, :] = rng.normal(size=(3, 4))
orig_zooms = voxel_sizes(orig_aff)
orig_zooms = voxel_sizes(orig_aff) # noqa: F841
orig_axcodes = aff2axcodes(orig_aff)
orig_centroid = apply_affine(orig_aff, (orig_shape - 1) // 2)

Expand Down
6 changes: 3 additions & 3 deletions nibabel/tests/test_arraywriters.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ def test_slope_inter_castable():
for out_dtt in NUMERIC_TYPES:
for klass in (ArrayWriter, SlopeArrayWriter, SlopeInterArrayWriter):
arr = np.zeros((5,), dtype=in_dtt)
aw = klass(arr, out_dtt) # no error
_ = klass(arr, out_dtt) # no error
# Test special case of none finite
# This raises error for ArrayWriter, but not for the others
arr = np.array([np.inf, np.nan, -np.inf])
Expand All @@ -285,8 +285,8 @@ def test_slope_inter_castable():
in_arr = arr.astype(in_dtt)
with pytest.raises(WriterError):
ArrayWriter(in_arr, out_dtt)
aw = SlopeArrayWriter(arr.astype(in_dtt), out_dtt) # no error
aw = SlopeInterArrayWriter(arr.astype(in_dtt), out_dtt) # no error
_ = SlopeArrayWriter(arr.astype(in_dtt), out_dtt) # no error
_ = SlopeInterArrayWriter(arr.astype(in_dtt), out_dtt) # no error
for in_dtt, out_dtt, arr, slope_only, slope_inter, neither in (
(np.float32, np.float32, 1, True, True, True),
(np.float64, np.float32, 1, True, True, True),
Expand Down
Loading

0 comments on commit 90f5d3b

Please sign in to comment.