Skip to content

Commit 24d5acb

Browse files
committed
ENH: Add type annotations to pacify mypy
1 parent 2d7d1b2 commit 24d5acb

24 files changed

+90
-83
lines changed

nibabel/analyze.py

+10-7
Original file line numberDiff line numberDiff line change
@@ -81,14 +81,17 @@
8181
can be loaded with and without a default flip, so the saved zoom will not
8282
constrain the affine.
8383
"""
84+
from __future__ import annotations
85+
86+
from typing import Type
8487

8588
import numpy as np
8689

8790
from .arrayproxy import ArrayProxy
8891
from .arraywriters import ArrayWriter, WriterError, get_slope_inter, make_array_writer
8992
from .batteryrunners import Report
9093
from .fileholders import copy_file_map
91-
from .spatialimages import HeaderDataError, HeaderTypeError, SpatialImage
94+
from .spatialimages import HeaderDataError, HeaderTypeError, SpatialHeader, SpatialImage
9295
from .volumeutils import (
9396
apply_read_scaling,
9497
array_from_file,
@@ -131,7 +134,7 @@
131134
('glmax', 'i4'),
132135
('glmin', 'i4'),
133136
]
134-
data_history_dtd = [
137+
data_history_dtd: list[tuple[str, str] | tuple[str, str, tuple[int, ...]]] = [
135138
('descrip', 'S80'),
136139
('aux_file', 'S24'),
137140
('orient', 'S1'),
@@ -172,7 +175,7 @@
172175
data_type_codes = make_dt_codes(_dtdefs)
173176

174177

175-
class AnalyzeHeader(LabeledWrapStruct):
178+
class AnalyzeHeader(LabeledWrapStruct, SpatialHeader):
176179
"""Class for basic analyze header
177180
178181
Implements zoom-only setting of affine transform, and no image
@@ -892,11 +895,11 @@ def may_contain_header(klass, binaryblock):
892895
class AnalyzeImage(SpatialImage):
893896
"""Class for basic Analyze format image"""
894897

895-
header_class = AnalyzeHeader
898+
header_class: Type[AnalyzeHeader] = AnalyzeHeader
896899
_meta_sniff_len = header_class.sizeof_hdr
897-
files_types = (('image', '.img'), ('header', '.hdr'))
898-
valid_exts = ('.img', '.hdr')
899-
_compressed_suffixes = ('.gz', '.bz2', '.zst')
900+
files_types: tuple[tuple[str, str], ...] = (('image', '.img'), ('header', '.hdr'))
901+
valid_exts: tuple[str, ...] = ('.img', '.hdr')
902+
_compressed_suffixes: tuple[str, ...] = ('.gz', '.bz2', '.zst')
900903

901904
makeable = True
902905
rw = True

nibabel/benchmarks/bench_arrayproxy_slicing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626

2727
# if memory_profiler is installed, we get memory usage results
2828
try:
29-
from memory_profiler import memory_usage
29+
from memory_profiler import memory_usage # type: ignore
3030
except ImportError:
3131
memory_usage = None
3232

nibabel/brikhead.py

-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,6 @@
2727
am aware) always be >= 1. This permits sub-brick indexing common in AFNI
2828
programs (e.g., example4d+orig'[0]').
2929
"""
30-
3130
import os
3231
import re
3332
from copy import deepcopy

nibabel/casting.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
Most routines work round some numpy oddities in floating point precision and
44
casting. Others work round numpy casting to and from python ints
55
"""
6+
from __future__ import annotations
67

78
import warnings
89
from numbers import Integral
@@ -110,7 +111,7 @@ def float_to_int(arr, int_type, nan2zero=True, infmax=False):
110111

111112

112113
# Cache range values
113-
_SHARED_RANGES = {}
114+
_SHARED_RANGES: dict[tuple[type, type], tuple[np.number, np.number]] = {}
114115

115116

116117
def shared_range(flt_type, int_type):

nibabel/cmdline/dicomfs.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ class dummy_fuse:
2525

2626

2727
try:
28-
import fuse
28+
import fuse # type: ignore
2929

3030
uid = os.getuid()
3131
gid = os.getgid()

nibabel/ecat.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@
5050

5151
from .arraywriters import make_array_writer
5252
from .fileslice import canonical_slicers, predict_shape, slice2outax
53-
from .spatialimages import SpatialImage
53+
from .spatialimages import SpatialHeader, SpatialImage
5454
from .volumeutils import array_from_file, make_dt_codes, native_code, swapped_code
5555
from .wrapstruct import WrapStruct
5656

@@ -243,7 +243,7 @@
243243
patient_orient_neurological = [1, 3, 5, 7]
244244

245245

246-
class EcatHeader(WrapStruct):
246+
class EcatHeader(WrapStruct, SpatialHeader):
247247
"""Class for basic Ecat PET header
248248
249249
Sub-parts of standard Ecat File

nibabel/externals/netcdf.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -871,6 +871,7 @@ def __setattr__(self, attr, value):
871871
pass
872872
self.__dict__[attr] = value
873873

874+
@property
874875
def isrec(self):
875876
"""Returns whether the variable has a record dimension or not.
876877
@@ -881,16 +882,15 @@ def isrec(self):
881882
882883
"""
883884
return bool(self.data.shape) and not self._shape[0]
884-
isrec = property(isrec)
885885

886+
@property
886887
def shape(self):
887888
"""Returns the shape tuple of the data variable.
888889
889890
This is a read-only attribute and can not be modified in the
890891
same manner of other numpy arrays.
891892
"""
892893
return self.data.shape
893-
shape = property(shape)
894894

895895
def getValue(self):
896896
"""

nibabel/filebasedimages.py

+9-7
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@
77
#
88
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
99
"""Common interface for any image format--volume or surface, binary or xml."""
10+
from __future__ import annotations
1011

1112
import io
1213
from copy import deepcopy
14+
from typing import Type
1315
from urllib import request
1416

1517
from .fileholders import FileHolder
@@ -144,14 +146,14 @@ class FileBasedImage:
144146
work.
145147
"""
146148

147-
header_class = FileBasedHeader
148-
_meta_sniff_len = 0
149-
files_types = (('image', None),)
150-
valid_exts = ()
151-
_compressed_suffixes = ()
149+
header_class: Type[FileBasedHeader] = FileBasedHeader
150+
_meta_sniff_len: int = 0
151+
files_types: tuple[tuple[str, str | None], ...] = (('image', None),)
152+
valid_exts: tuple[str, ...] = ()
153+
_compressed_suffixes: tuple[str, ...] = ()
152154

153-
makeable = True # Used in test code
154-
rw = True # Used in test code
155+
makeable: bool = True # Used in test code
156+
rw: bool = True # Used in test code
155157

156158
def __init__(self, header=None, extra=None, file_map=None):
157159
"""Initialize image

nibabel/freesurfer/mghformat.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from ..fileholders import FileHolder
2222
from ..filename_parser import _stringify_path
2323
from ..openers import ImageOpener
24-
from ..spatialimages import HeaderDataError, SpatialImage
24+
from ..spatialimages import HeaderDataError, SpatialHeader, SpatialImage
2525
from ..volumeutils import Recoder, array_from_file, array_to_file, endian_codes
2626
from ..wrapstruct import LabeledWrapStruct
2727

@@ -87,7 +87,7 @@ class MGHError(Exception):
8787
"""
8888

8989

90-
class MGHHeader(LabeledWrapStruct):
90+
class MGHHeader(LabeledWrapStruct, SpatialHeader):
9191
"""Class for MGH format header
9292
9393
The header also consists of the footer data which MGH places after the data

nibabel/gifti/gifti.py

+10-5
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@
1111
The Gifti specification was (at time of writing) available as a PDF download
1212
from http://www.nitrc.org/projects/gifti/
1313
"""
14+
from __future__ import annotations
1415

1516
import base64
1617
import sys
1718
import warnings
19+
from typing import Type
1820

1921
import numpy as np
2022

@@ -577,7 +579,7 @@ class GiftiImage(xml.XmlSerializable, SerializableImage):
577579
# The parser will in due course be a GiftiImageParser, but we can't set
578580
# that now, because it would result in a circular import. We set it after
579581
# the class has been defined, at the end of the class definition.
580-
parser = None
582+
parser: Type[xml.XmlParser]
581583

582584
def __init__(
583585
self,
@@ -832,17 +834,20 @@ def _to_xml_element(self):
832834
GIFTI.append(dar._to_xml_element())
833835
return GIFTI
834836

835-
def to_xml(self, enc='utf-8'):
837+
def to_xml(self, enc='utf-8') -> bytes:
836838
"""Return XML corresponding to image content"""
837839
header = b"""<?xml version="1.0" encoding="UTF-8"?>
838840
<!DOCTYPE GIFTI SYSTEM "http://www.nitrc.org/frs/download.php/115/gifti.dtd">
839841
"""
840842
return header + super().to_xml(enc)
841843

842844
# Avoid the indirection of going through to_file_map
843-
to_bytes = to_xml
845+
def to_bytes(self, enc='utf-8'):
846+
return self.to_xml(enc=enc)
844847

845-
def to_file_map(self, file_map=None):
848+
to_bytes.__doc__ = SerializableImage.to_bytes.__doc__
849+
850+
def to_file_map(self, file_map=None, enc='utf-8'):
846851
"""Save the current image to the specified file_map
847852
848853
Parameters
@@ -858,7 +863,7 @@ def to_file_map(self, file_map=None):
858863
if file_map is None:
859864
file_map = self.file_map
860865
with file_map['image'].get_prepare_fileobj('wb') as f:
861-
f.write(self.to_xml())
866+
f.write(self.to_xml(enc=enc))
862867

863868
@classmethod
864869
def from_file_map(klass, file_map, buffer_size=35000000, mmap=True):

nibabel/minc1.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@
77
#
88
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
99
"""Read MINC1 format images"""
10+
from __future__ import annotations
1011

1112
from numbers import Integral
13+
from typing import Type
1214

1315
import numpy as np
1416

@@ -305,11 +307,11 @@ class Minc1Image(SpatialImage):
305307
load.
306308
"""
307309

308-
header_class = Minc1Header
309-
_meta_sniff_len = 4
310-
valid_exts = ('.mnc',)
311-
files_types = (('image', '.mnc'),)
312-
_compressed_suffixes = ('.gz', '.bz2', '.zst')
310+
header_class: Type[MincHeader] = Minc1Header
311+
_meta_sniff_len: int = 4
312+
valid_exts: tuple[str, ...] = ('.mnc',)
313+
files_types: tuple[tuple[str, str], ...] = (('image', '.mnc'),)
314+
_compressed_suffixes: tuple[str, ...] = ('.gz', '.bz2', '.zst')
313315

314316
makeable = True
315317
rw = False

nibabel/minc2.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ class Minc2Image(Minc1Image):
155155
def from_file_map(klass, file_map, *, mmap=True, keep_file_open=None):
156156
# Import of h5py might take awhile for MPI-enabled builds
157157
# So we are importing it here "on demand"
158-
import h5py
158+
import h5py # type: ignore
159159

160160
holder = file_map['image']
161161
if holder.filename is None:

nibabel/nicom/dicomwrappers.py

-2
Original file line numberDiff line numberDiff line change
@@ -127,8 +127,6 @@ class Wrapper:
127127
is_multiframe = False
128128
b_matrix = None
129129
q_vector = None
130-
b_value = None
131-
b_vector = None
132130

133131
def __init__(self, dcm_data):
134132
"""Initialize wrapper

nibabel/nifti1.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,11 @@
1010
1111
NIfTI1 format defined at http://nifti.nimh.nih.gov/nifti-1/
1212
"""
13+
from __future__ import annotations
14+
1315
import warnings
1416
from io import BytesIO
17+
from typing import Type
1518

1619
import numpy as np
1720
import numpy.linalg as npl
@@ -87,8 +90,8 @@
8790
# datatypes not in analyze format, with codes
8891
if have_binary128():
8992
# Only enable 128 bit floats if we really have IEEE binary 128 longdoubles
90-
_float128t = np.longdouble
91-
_complex256t = np.longcomplex
93+
_float128t: Type[np.generic] = np.longdouble
94+
_complex256t: Type[np.generic] = np.longcomplex
9295
else:
9396
_float128t = np.void
9497
_complex256t = np.void
@@ -1814,7 +1817,7 @@ class Nifti1PairHeader(Nifti1Header):
18141817
class Nifti1Pair(analyze.AnalyzeImage):
18151818
"""Class for NIfTI1 format image, header pair"""
18161819

1817-
header_class = Nifti1PairHeader
1820+
header_class: Type[Nifti1Header] = Nifti1PairHeader
18181821
_meta_sniff_len = header_class.sizeof_hdr
18191822
rw = True
18201823

@@ -1848,9 +1851,7 @@ def __init__(self, dataobj, affine, header=None, extra=None, file_map=None, dtyp
18481851
self._affine2header()
18491852

18501853
# Copy docstring
1851-
__init__.__doc__ = (
1852-
analyze.AnalyzeImage.__init__.__doc__
1853-
+ """
1854+
__init__.__doc__ = f"""{analyze.AnalyzeImage.__init__.__doc__}
18541855
Notes
18551856
-----
18561857
@@ -1863,7 +1864,6 @@ def __init__(self, dataobj, affine, header=None, extra=None, file_map=None, dtyp
18631864
:meth:`set_qform` methods can be used to update the codes after an image
18641865
has been created - see those methods, and the :ref:`manual
18651866
<default-sform-qform-codes>` for more details. """
1866-
)
18671867

18681868
def update_header(self):
18691869
"""Harmonize header with image data and affine

nibabel/openers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
# is indexed_gzip present and modern?
2222
try:
23-
import indexed_gzip as igzip
23+
import indexed_gzip as igzip # type: ignore
2424

2525
version = igzip.__version__
2626

nibabel/parrec.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1338,7 +1338,7 @@ def from_filename(
13381338
strict_sort=strict_sort,
13391339
)
13401340

1341-
load = from_filename
1341+
load = from_filename # type: ignore
13421342

13431343

1344-
load = PARRECImage.load
1344+
load = PARRECImage.from_filename

nibabel/pkg_info.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def cmp_pkg_version(version_str: str, pkg_version_str: str = __version__) -> int
7070
return _cmp(Version(version_str), Version(pkg_version_str))
7171

7272

73-
def pkg_commit_hash(pkg_path: str = None) -> tuple[str, str]:
73+
def pkg_commit_hash(pkg_path: str | None = None) -> tuple[str, str]:
7474
"""Get short form of commit hash
7575
7676
In this file is a variable called COMMIT_HASH. This contains a substitution
@@ -109,7 +109,7 @@ def pkg_commit_hash(pkg_path: str = None) -> tuple[str, str]:
109109
cwd=pkg_path,
110110
)
111111
if proc.stdout:
112-
return 'repository', proc.stdout.strip()
112+
return 'repository', proc.stdout.decode().strip()
113113
return '(none found)', '<not found>'
114114

115115

0 commit comments

Comments
 (0)