Skip to content

Commit 23223dc

Browse files
authored
Add type hint checking with mypy (#460)
* Add type hint checking with mypy * Fix EntryPoints import * Fix cachedprotocolmeta typing * Add release notes * Run ruff-format * pre-commit fixes * More mypy fixes * Fix release not location * Remove type checking guards * Some zarr3 typing fixes * Fix inheritance * Final zarr3 typing fixes
1 parent 07755d1 commit 23223dc

15 files changed

+100
-51
lines changed

.pre-commit-config.yaml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,10 @@ repos:
2525
rev: 2024.08.19
2626
hooks:
2727
- id: sp-repo-review
28+
29+
- repo: https://github.com/pre-commit/mirrors-mypy
30+
rev: 'v1.4.0'
31+
hooks:
32+
- id: mypy
33+
args: [--config-file, pyproject.toml]
34+
additional_dependencies: [numpy, pytest, zfpy, 'zarr==3.0.0b1']

docs/conf.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
# All configuration values have a default; values that are commented out
1313
# serve to show the default.
1414

15-
1615
import os
1716
import sys
1817
from unittest.mock import Mock as MagicMock
@@ -232,7 +231,7 @@ def __getattr__(cls, name):
232231

233232
# -- Options for LaTeX output ---------------------------------------------
234233

235-
latex_elements = {
234+
latex_elements: dict[str, str] = {
236235
# The paper size ('letterpaper' or 'a4paper').
237236
#'papersize': 'letterpaper',
238237
# The font size ('10pt', '11pt' or '12pt').

docs/release.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ Enhancements
2626
By :user:`Norman Rzepka <normanrz>`, :issue:`613`.
2727
* Add codec wrappers for Zarr 3.
2828
By :user:`Norman Rzepka <normanrz>`, :issue:`524`
29+
* Added mypy type checking to continuous integration.
30+
By :user:`David Stansby <dstansby>`, :issue:`460`.
2931

3032
Maintenance
3133
~~~~~~~~~~~

numcodecs/abc.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,13 +29,14 @@
2929
"""
3030

3131
from abc import ABC, abstractmethod
32+
from typing import Optional
3233

3334

3435
class Codec(ABC):
3536
"""Codec abstract base class."""
3637

3738
# override in sub-class
38-
codec_id = None
39+
codec_id: Optional[str] = None
3940
"""Codec identifier."""
4041

4142
@abstractmethod

numcodecs/checksum32.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,23 @@
11
import struct
22
import zlib
3-
from typing import Literal
3+
from collections.abc import Callable
4+
from typing import TYPE_CHECKING, Literal
45

56
import numpy as np
67

78
from .abc import Codec
89
from .compat import ensure_contiguous_ndarray, ndarray_copy
910
from .jenkins import jenkins_lookup3
1011

12+
if TYPE_CHECKING:
13+
from typing_extensions import Buffer
14+
1115
CHECKSUM_LOCATION = Literal['start', 'end']
1216

1317

1418
class Checksum32(Codec):
1519
# override in sub-class
16-
checksum = None
20+
checksum: Callable[["Buffer", int], int] | None = None
1721
location: CHECKSUM_LOCATION = 'start'
1822

1923
def __init__(self, location: CHECKSUM_LOCATION | None = None):

numcodecs/compat.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def ensure_contiguous_ndarray_like(buf, max_buffer_size=None, flatten=True) -> N
100100

101101
# check for datetime or timedelta ndarray, the buffer interface doesn't support those
102102
if arr.dtype.kind in "Mm":
103-
arr = arr.view(np.int64)
103+
arr = arr.view(np.int64) # type: ignore[arg-type]
104104

105105
# check memory is contiguous, if so flatten
106106
if arr.flags.c_contiguous or arr.flags.f_contiguous:
@@ -117,7 +117,7 @@ def ensure_contiguous_ndarray_like(buf, max_buffer_size=None, flatten=True) -> N
117117
return arr
118118

119119

120-
def ensure_contiguous_ndarray(buf, max_buffer_size=None, flatten=True) -> np.array:
120+
def ensure_contiguous_ndarray(buf, max_buffer_size=None, flatten=True) -> np.ndarray:
121121
"""Convenience function to coerce `buf` to a numpy array, if it is not already a
122122
numpy array. Also ensures that the returned value exports fully contiguous memory,
123123
and supports the new-style buffer interface. If the optional max_buffer_size is

numcodecs/lzma.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1-
import contextlib
1+
from types import ModuleType
2+
from typing import Optional
23

3-
_lzma = None
4+
_lzma: Optional[ModuleType] = None
45
try:
56
import lzma as _lzma
67
except ImportError: # pragma: no cover
7-
with contextlib.suppress(ImportError):
8-
from backports import lzma as _lzma
8+
try:
9+
from backports import lzma as _lzma # type: ignore[no-redef]
10+
except ImportError:
11+
pass
912

1013

1114
if _lzma:

numcodecs/ndarray_like.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from typing import Any, ClassVar, Optional, Protocol, runtime_checkable
22

33

4-
class _CachedProtocolMeta(Protocol.__class__):
4+
class _CachedProtocolMeta(Protocol.__class__): # type: ignore[name-defined]
55
"""Custom implementation of @runtime_checkable
66
77
The native implementation of @runtime_checkable is slow,

numcodecs/registry.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@
22
applications to dynamically register and look-up codec classes."""
33

44
import logging
5-
from importlib.metadata import entry_points
5+
from importlib.metadata import EntryPoints, entry_points
6+
7+
from numcodecs.abc import Codec
68

79
logger = logging.getLogger("numcodecs")
8-
codec_registry = {}
9-
entries = {}
10+
codec_registry: dict[str, Codec] = {}
11+
entries: dict[str, "EntryPoints"] = {}
1012

1113

1214
def run_entrypoints():

numcodecs/tests/test_lzma.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import itertools
22
import unittest
3+
from types import ModuleType
4+
from typing import cast
35

46
import numpy as np
57
import pytest
@@ -20,6 +22,8 @@
2022
check_repr,
2123
)
2224

25+
_lzma = cast(ModuleType, _lzma)
26+
2327
codecs = [
2428
LZMA(),
2529
LZMA(preset=1),

0 commit comments

Comments
 (0)