diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index bec8fb69..c31ea29e 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -162,6 +162,17 @@ jobs: - name: pyright (strict type tests) run: pyright -p tests/typing + - name: stubtest (Cython stubs against the built extensions) + # Read the stubs from src/: mypy ignores the installed copies until numcodecs + # ships a py.typed marker. + env: + MYPYPATH: src + run: | + python -m mypy.stubtest --mypy-config-file pyproject.toml \ + --allowlist tests/typing/stubtest-allowlist.txt \ + numcodecs.blosc numcodecs.zstd numcodecs.lz4 numcodecs.vlen \ + numcodecs.fletcher32 numcodecs.jenkins numcodecs.compat_ext numcodecs._shuffle + test-zarr: runs-on: ubuntu-latest strategy: diff --git a/docs/abc.md b/docs/abc.md index f080766f..925757c2 100644 --- a/docs/abc.md +++ b/docs/abc.md @@ -10,4 +10,16 @@ .. automethod:: decode .. automethod:: get_config .. automethod:: from_config + +Protocols +--------- + +These describe codecs structurally, for code that accepts any object implementing the +interface whether or not it subclasses :class:`Codec`. The three kinds mirror the codec +kinds of the Zarr version 3 specification. + +.. autoclass:: CodecProtocol +.. autoclass:: BytesBytesCodec +.. autoclass:: ArrayArrayCodec +.. autoclass:: ArrayBytesCodec ``` diff --git a/docs/release.md b/docs/release.md index 51e2933b..abeff1b4 100644 --- a/docs/release.md +++ b/docs/release.md @@ -47,6 +47,40 @@ ndarray, and raises `ValueError` when `out` has the wrong size. * `Fletcher32.decode` without `out` returns a `uint8` ndarray, like the other checksum codecs, instead of a Cython memoryview slice. +* Correct type annotations that described something other than what the code does: + `numcodecs.registry.codec_registry` holds codec classes (`dict[str, type[Codec]]`) and + `entries` holds single entry points (`dict[str, EntryPoint]`). `numcodecs.compat` + functions now annotate their parameters, and `ndarray_copy` returns the type of `dst` + (or of `src` when `dst` is `None`). The `NDArrayLike`, `DType` and `FlagsObj` protocols + declare read-only properties, so `numpy.ndarray` now satisfies `NDArrayLike` for type + checkers, and `numcodecs.ndarray_like.BufferLike` names "a buffer or an ndarray-like". +* `numcodecs` defines `__all__`, so type checkers treat its re-exported codec classes as + public. `from numcodecs import *` now imports only those names. +* `register_codec` raises `ValueError` for a class without a `codec_id` when no id is + given, instead of registering it under `None`. +* `Codec.codec_id` no longer defaults to `None`. Abstract intermediate classes such as + `Checksum32` leave it unset, so reading it raises `AttributeError`; every concrete codec + sets it. + +### Enhancements + +* Annotate `numcodecs.abc.Codec`. `encode` and `decode` take and return + `numcodecs.ndarray_like.BufferLike` (an object exporting the buffer protocol, or an + ndarray-like), with `buf` positional-only, and `decode(buf, out=out)` is typed to return + the type of `out`. `get_config` returns `Mapping[str, Any]` and `from_config` returns + `Self`. Previously pyright inferred that `encode` and `decode` return `None`. +* Add structural protocols `numcodecs.abc.CodecProtocol`, `BytesBytesCodec`, + `ArrayArrayCodec` and `ArrayBytesCodec` for code that accepts any object implementing the + codec interface. +* Ship `.pyi` type stubs for the Cython extension modules (`blosc`, `zstd`, `lz4`, `vlen`, + `fletcher32`, `jenkins`, `compat_ext` and `_shuffle`), checked against the compiled + modules with `mypy.stubtest` in CI. Type checkers previously saw the Blosc, Zstd, LZ4, + Fletcher32 and VLen codecs as unknown. + +### Deprecations + +* Loading a codec through the `numcodecs.codecs` entry point group whose class does not + subclass `numcodecs.abc.Codec` now emits a `DeprecationWarning`. (release_0.17.1)= diff --git a/pyproject.toml b/pyproject.toml index 721d1812..3050fdfc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -245,6 +245,7 @@ quote-style = "preserve" [tool.mypy] ignore_errors = false ignore_missing_imports = true +python_version = "3.12" enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool"] # TODO: set options below to true strict = false diff --git a/src/numcodecs/__init__.py b/src/numcodecs/__init__.py index be60bfc3..bad41090 100644 --- a/src/numcodecs/__init__.py +++ b/src/numcodecs/__init__.py @@ -25,6 +25,42 @@ from numcodecs.registry import get_codec as get_codec from numcodecs.registry import register_codec +# Names listed here are the public API re-exported from submodules. Optional codecs are +# appended below when their dependency imports. +__all__ = [ + "BZ2", + "CRC32", + "JSON", + "LZ4", + "LZMA", + "Adler32", + "AsType", + "Base64", + "BitRound", + "Blosc", + "Categorize", + "Delta", + "FixedScaleOffset", + "Fletcher32", + "GZip", + "JenkinsLookup3", + "PackBits", + "Pickle", + "Quantize", + "Shuffle", + "VLenArray", + "VLenBytes", + "VLenUTF8", + "Zlib", + "Zstd", + "blosc", + "get_codec", + "lz4", + "register_codec", + "vlen", + "zstd", +] + __version__: str = _version("numcodecs") from numcodecs.zlib import Zlib @@ -131,18 +167,22 @@ from numcodecs.zfpy import ZFPY register_codec(ZFPY) + __all__ += ["ZFPY"] with suppress(ImportError): from numcodecs.msgpacks import MsgPack register_codec(MsgPack) + __all__ += ["MsgPack"] with suppress(ImportError): from numcodecs.checksum32 import CRC32C register_codec(CRC32C) + __all__ += ["CRC32C"] with suppress(ImportError): from numcodecs.pcodec import PCodec register_codec(PCodec) + __all__ += ["PCodec"] diff --git a/src/numcodecs/_shuffle.pyi b/src/numcodecs/_shuffle.pyi new file mode 100644 index 00000000..a8041848 --- /dev/null +++ b/src/numcodecs/_shuffle.pyi @@ -0,0 +1,4 @@ +from collections.abc import Buffer + +def _doShuffle(src: Buffer, des: Buffer, element_size: int) -> None: ... +def _doUnshuffle(src: Buffer, des: Buffer, element_size: int) -> None: ... diff --git a/src/numcodecs/abc.py b/src/numcodecs/abc.py index 6865df09..fd955569 100644 --- a/src/numcodecs/abc.py +++ b/src/numcodecs/abc.py @@ -29,17 +29,31 @@ """ from abc import ABC, abstractmethod +from collections.abc import Buffer, Mapping +from typing import Any, Protocol, Self, overload + +from .ndarray_like import BufferLike, NDArrayLike + +__all__ = [ + "ArrayArrayCodec", + "ArrayBytesCodec", + "BytesBytesCodec", + "Codec", + "CodecProtocol", +] class Codec(ABC): """Codec abstract base class.""" - # override in sub-class - codec_id: str | None = None - """Codec identifier.""" + # Declared without a value (abstract intermediate classes leave it unset) and without + # `ClassVar`, so that `Codec` instances match protocols that declare `codec_id` either + # as a plain attribute or as a read-only property. + codec_id: str + """Codec identifier. Every concrete codec class sets it as a class attribute.""" @abstractmethod - def encode(self, buf): # pragma: no cover + def encode(self, buf: BufferLike, /) -> BufferLike: # pragma: no cover """Encode data in `buf`. Parameters @@ -55,8 +69,14 @@ def encode(self, buf): # pragma: no cover protocol. """ + @overload + def decode(self, buf: BufferLike, /, out: None = None) -> BufferLike: ... + @overload + def decode[OutT: BufferLike](self, buf: BufferLike, /, out: OutT) -> OutT: ... @abstractmethod - def decode(self, buf, out=None): # pragma: no cover + def decode( + self, buf: BufferLike, /, out: BufferLike | None = None + ) -> BufferLike: # pragma: no cover """Decode data in `buf`. Parameters @@ -72,10 +92,10 @@ def decode(self, buf, out=None): # pragma: no cover ------- dec : buffer-like Decoded data. May be any object supporting the new-style - buffer protocol. + buffer protocol. If `out` was provided, `out` itself. """ - def get_config(self): + def get_config(self) -> Mapping[str, Any]: """Return a dictionary holding configuration parameters for this codec. Must include an 'id' field with the codec identifier. All values must be compatible with JSON encoding.""" @@ -83,7 +103,7 @@ def get_config(self): # override in sub-class if need special encoding of config values # setup config object - config = {'id': self.codec_id} + config: dict[str, Any] = {'id': self.codec_id} # by default, assume all non-private members are configuration # parameters - override this in sub-class if not the case @@ -94,8 +114,8 @@ def get_config(self): return config @classmethod - def from_config(cls, config): - """Instantiate codec from a configuration object.""" + def from_config(cls, config: Mapping[str, Any], /) -> Self: + """Instantiate codec from a configuration object, without its 'id' field.""" # N.B., assume at this point the 'id' field has been removed from # the config object @@ -105,14 +125,14 @@ def from_config(cls, config): # keyword arguments without any special decoding return cls(**config) - def __eq__(self, other): + def __eq__(self, other: object) -> bool: # override in sub-class if need special equality comparison try: - return self.get_config() == other.get_config() + return bool(self.get_config() == other.get_config()) # type: ignore[attr-defined] except AttributeError: return False - def __repr__(self): + def __repr__(self) -> str: # override in sub-class if need special representation # by default, assume all non-private members are configuration @@ -124,3 +144,44 @@ def __repr__(self): ] r += ', '.join(params) + ')' return r + + +class CodecProtocol(Protocol): + """The structural interface of a codec, for code that accepts any object implementing + it, whether or not it subclasses `Codec`.""" + + @property + def codec_id(self) -> str: ... # pragma: no cover + + def encode(self, buf: BufferLike, /) -> BufferLike: ... # pragma: no cover + + def decode(self, buf: BufferLike, /, out: Any = None) -> BufferLike: ... # pragma: no cover + + def get_config(self) -> Mapping[str, Any]: ... # pragma: no cover + + @classmethod + def from_config(cls, config: Mapping[str, Any], /) -> Self: ... # pragma: no cover + + +class BytesBytesCodec(CodecProtocol, Protocol): + """A codec that maps bytes to bytes, such as a compressor or a checksum.""" + + def encode(self, buf: BufferLike, /) -> Buffer: ... # pragma: no cover + + def decode(self, buf: BufferLike, /, out: Any = None) -> Buffer: ... # pragma: no cover + + +class ArrayArrayCodec(CodecProtocol, Protocol): + """A codec that maps an array to an array, such as a filter.""" + + def encode(self, buf: BufferLike, /) -> NDArrayLike: ... # pragma: no cover + + def decode(self, buf: BufferLike, /, out: Any = None) -> NDArrayLike: ... # pragma: no cover + + +class ArrayBytesCodec(CodecProtocol, Protocol): + """A codec that serializes an array to bytes and back.""" + + def encode(self, buf: BufferLike, /) -> Buffer: ... # pragma: no cover + + def decode(self, buf: BufferLike, /, out: Any = None) -> NDArrayLike: ... # pragma: no cover diff --git a/src/numcodecs/blosc.pyi b/src/numcodecs/blosc.pyi new file mode 100644 index 00000000..ca11c245 --- /dev/null +++ b/src/numcodecs/blosc.pyi @@ -0,0 +1,68 @@ +from typing import Final, overload + +from .abc import Codec +from .ndarray_like import BufferLike + +NOSHUFFLE: Final[int] +SHUFFLE: Final[int] +BITSHUFFLE: Final[int] +AUTOSHUFFLE: Final[int] +AUTOBLOCKS: Final[int] +MAX_OVERHEAD: Final[int] +MAX_BUFFERSIZE: Final[int] +MAX_THREADS: Final[int] +MAX_TYPESIZE: Final[int] +VERSION_STRING: Final[str] +VERSION_DATE: Final[str] +__version__: Final[str] + +use_threads: bool | None +"""Set to `True` or `False` to override whether Blosc may use threads; `None` (the +default) decides from the calling thread and process.""" + +def _init() -> None: ... +def _destroy() -> None: ... +def _get_use_threads() -> bool: ... +def _cbuffer_sizes(source: BufferLike) -> tuple[int, int, int]: ... +def _cbuffer_metainfo(source: BufferLike) -> tuple[int, bool, bool]: ... +def list_compressors() -> list[str]: ... +def get_nthreads() -> int: ... +def set_nthreads(nthreads: int) -> int: ... +def cbuffer_complib(source: BufferLike) -> str: ... +def compress( + source: BufferLike, + cname: bytes, + clevel: int, + shuffle: int = ..., + blocksize: int = ..., + typesize: int | None = None, +) -> bytes: ... +@overload +def decompress(source: BufferLike, dest: None = None) -> bytes: ... +@overload +def decompress[OutT: BufferLike](source: BufferLike, dest: OutT) -> OutT: ... + +class Blosc(Codec): + codec_id: str + NOSHUFFLE: int + SHUFFLE: int + BITSHUFFLE: int + AUTOSHUFFLE: int + max_buffer_size: int + cname: str + clevel: int + shuffle: int + blocksize: int + def __init__( + self, + cname: str = "lz4", + clevel: int = 5, + shuffle: int = ..., + blocksize: int = ..., + typesize: int | None = None, + ) -> None: ... + def encode(self, buf: BufferLike) -> bytes: ... + @overload + def decode(self, buf: BufferLike, out: None = None) -> bytes: ... + @overload + def decode[OutT: BufferLike](self, buf: BufferLike, out: OutT) -> OutT: ... diff --git a/src/numcodecs/checksum32.py b/src/numcodecs/checksum32.py index a095b171..70094ccc 100644 --- a/src/numcodecs/checksum32.py +++ b/src/numcodecs/checksum32.py @@ -89,7 +89,7 @@ def decode(self, buf, out=None): @staticmethod @abc.abstractmethod - def checksum(data: Buffer, value: int) -> int: ... + def checksum(data: Buffer, value: int, /) -> int: ... class CRC32(Checksum32): @@ -151,7 +151,7 @@ class JenkinsLookup3(Checksum32): bytes prepended to the buffer before evaluating the hash, default: None """ - checksum = jenkins_lookup3 + checksum = staticmethod(jenkins_lookup3) codec_id = "jenkins_lookup3" def __init__(self, initval: int = 0, prefix=None): diff --git a/src/numcodecs/compat.py b/src/numcodecs/compat.py index cc4d2d13..bad12fd4 100644 --- a/src/numcodecs/compat.py +++ b/src/numcodecs/compat.py @@ -1,12 +1,19 @@ import array import codecs +from collections.abc import Buffer +from typing import Any, overload import numpy as np +import numpy.typing as npt -from .ndarray_like import NDArrayLike, is_ndarray_like +from .ndarray_like import BufferLike, NDArrayLike, is_ndarray_like -def ensure_ndarray_like(buf) -> NDArrayLike: +@overload +def ensure_ndarray_like(buf: Buffer) -> npt.NDArray[Any]: ... +@overload +def ensure_ndarray_like(buf: NDArrayLike) -> NDArrayLike: ... +def ensure_ndarray_like(buf: BufferLike) -> NDArrayLike: """Convenience function to coerce `buf` to ndarray-like array. Parameters @@ -41,7 +48,7 @@ def ensure_ndarray_like(buf) -> NDArrayLike: return buf -def ensure_ndarray(buf) -> np.ndarray: +def ensure_ndarray(buf: BufferLike) -> npt.NDArray[Any]: """Convenience function to coerce `buf` to a numpy array, if it is not already a numpy array. @@ -63,7 +70,17 @@ def ensure_ndarray(buf) -> np.ndarray: return np.array(ensure_ndarray_like(buf), copy=False) -def ensure_contiguous_ndarray_like(buf, max_buffer_size=None, flatten=True) -> NDArrayLike: +@overload +def ensure_contiguous_ndarray_like( + buf: Buffer, max_buffer_size: int | None = None, flatten: bool = True +) -> npt.NDArray[Any]: ... +@overload +def ensure_contiguous_ndarray_like( + buf: NDArrayLike, max_buffer_size: int | None = None, flatten: bool = True +) -> NDArrayLike: ... +def ensure_contiguous_ndarray_like( + buf: BufferLike, max_buffer_size: int | None = None, flatten: bool = True +) -> NDArrayLike: """Convenience function to coerce `buf` to ndarray-like array. Also ensures that the returned value exports fully contiguous memory, and supports the new-style buffer interface. If the optional max_buffer_size is @@ -95,12 +112,12 @@ def ensure_contiguous_ndarray_like(buf, max_buffer_size=None, flatten=True) -> N # check for object arrays, these are just memory pointers, actual memory holding # item data is scattered elsewhere - if arr.dtype == object: + if arr.dtype.kind == "O": raise TypeError("object arrays are not supported") # check for datetime or timedelta ndarray, the buffer interface doesn't support those if arr.dtype.kind in "Mm": - arr = arr.view(np.int64) # type: ignore[arg-type] + arr = arr.view(np.int64) # check memory is contiguous, if so flatten if arr.flags.c_contiguous or arr.flags.f_contiguous: @@ -117,7 +134,9 @@ def ensure_contiguous_ndarray_like(buf, max_buffer_size=None, flatten=True) -> N return arr -def ensure_contiguous_ndarray(buf, max_buffer_size=None, flatten=True) -> np.ndarray: +def ensure_contiguous_ndarray( + buf: BufferLike, max_buffer_size: int | None = None, flatten: bool = True +) -> npt.NDArray[Any]: """Convenience function to coerce `buf` to a numpy array, if it is not already a numpy array. Also ensures that the returned value exports fully contiguous memory, and supports the new-style buffer interface. If the optional max_buffer_size is @@ -150,7 +169,7 @@ def ensure_contiguous_ndarray(buf, max_buffer_size=None, flatten=True) -> np.nda ) -def ensure_bytes(buf) -> bytes: +def ensure_bytes(buf: BufferLike) -> bytes: """Obtain a bytes object from memory exposed by `buf`.""" if not isinstance(buf, bytes): @@ -158,7 +177,7 @@ def ensure_bytes(buf) -> bytes: # check for object arrays, these are just memory pointers, # actual memory holding item data is scattered elsewhere - if arr.dtype == object: + if arr.dtype.kind == "O": raise TypeError("object arrays are not supported") # create bytes @@ -167,14 +186,18 @@ def ensure_bytes(buf) -> bytes: return buf -def ensure_text(s, encoding="utf-8"): - if not isinstance(s, str): - s = ensure_contiguous_ndarray(s) - s = codecs.decode(s, encoding) - return s +def ensure_text(s: str | BufferLike, encoding: str = "utf-8") -> str: + """Return `s` if it is a `str`, else decode the bytes it exposes with `encoding`.""" + if isinstance(s, str): + return s + return codecs.decode(ensure_contiguous_ndarray(s), encoding) -def ndarray_copy(src, dst) -> NDArrayLike: +@overload +def ndarray_copy[SrcT: BufferLike](src: SrcT, dst: None) -> SrcT: ... +@overload +def ndarray_copy[DstT: BufferLike](src: BufferLike, dst: DstT) -> DstT: ... +def ndarray_copy(src: BufferLike, dst: BufferLike | None) -> BufferLike: """Copy the contents of the array from `src` to `dst`, and return `dst`. If `dst` is `None`, return `src` unchanged. Otherwise `dst` itself is returned, not @@ -185,28 +208,26 @@ def ndarray_copy(src, dst) -> NDArrayLike: # no-op return src - out = dst - # ensure ndarray like - src = ensure_ndarray_like(src) - dst = ensure_ndarray_like(dst) + src_arr: NDArrayLike = ensure_ndarray_like(src) + dst_arr: NDArrayLike = ensure_ndarray_like(dst) # flatten source array - src = src.reshape(-1, order="A") + src_arr = src_arr.reshape(-1, order="A") # ensure same data type - if dst.dtype != object: - src = src.view(dst.dtype) + if dst_arr.dtype.kind != "O": + src_arr = src_arr.view(dst_arr.dtype) # reshape source to match destination - if src.shape != dst.shape: - if dst.flags.f_contiguous: + if src_arr.shape != dst_arr.shape: + if dst_arr.flags.f_contiguous: order = "F" else: order = "C" - src = src.reshape(dst.shape, order=order) + src_arr = src_arr.reshape(dst_arr.shape, order=order) # copy via numpy - np.copyto(dst, src) + np.copyto(dst_arr, src_arr) # type: ignore[arg-type] # cupy arrays support copyto too - return out + return dst diff --git a/src/numcodecs/compat_ext.pyi b/src/numcodecs/compat_ext.pyi new file mode 100644 index 00000000..f5388bfb --- /dev/null +++ b/src/numcodecs/compat_ext.pyi @@ -0,0 +1,3 @@ +from collections.abc import Buffer + +def ensure_contiguous_memoryview(obj: Buffer) -> memoryview: ... diff --git a/src/numcodecs/fletcher32.pyi b/src/numcodecs/fletcher32.pyi new file mode 100644 index 00000000..0d9e7009 --- /dev/null +++ b/src/numcodecs/fletcher32.pyi @@ -0,0 +1,15 @@ +from typing import overload + +import numpy as np +import numpy.typing as npt + +from .abc import Codec +from .ndarray_like import BufferLike + +class Fletcher32(Codec): + codec_id: str + def encode(self, buf: BufferLike) -> bytes: ... + @overload + def decode(self, buf: BufferLike, out: None = None) -> npt.NDArray[np.uint8]: ... + @overload + def decode[OutT: BufferLike](self, buf: BufferLike, out: OutT) -> OutT: ... diff --git a/src/numcodecs/jenkins.pyi b/src/numcodecs/jenkins.pyi new file mode 100644 index 00000000..c8673b7f --- /dev/null +++ b/src/numcodecs/jenkins.pyi @@ -0,0 +1,3 @@ +from collections.abc import Buffer + +def jenkins_lookup3(_data: Buffer, initval: int = 0) -> int: ... diff --git a/src/numcodecs/lz4.pyi b/src/numcodecs/lz4.pyi new file mode 100644 index 00000000..b35f0972 --- /dev/null +++ b/src/numcodecs/lz4.pyi @@ -0,0 +1,24 @@ +from typing import Final, overload + +from .abc import Codec +from .ndarray_like import BufferLike + +VERSION_STRING: Final[str] +DEFAULT_ACCELERATION: Final[int] + +def compress(source: BufferLike, acceleration: int = ...) -> bytes: ... +@overload +def decompress(source: BufferLike, dest: None = None) -> bytes: ... +@overload +def decompress[OutT: BufferLike](source: BufferLike, dest: OutT) -> OutT: ... + +class LZ4(Codec): + codec_id: str + max_buffer_size: int + acceleration: int + def __init__(self, acceleration: int = ...) -> None: ... + def encode(self, buf: BufferLike) -> bytes: ... + @overload + def decode(self, buf: BufferLike, out: None = None) -> bytes: ... + @overload + def decode[OutT: BufferLike](self, buf: BufferLike, out: OutT) -> OutT: ... diff --git a/src/numcodecs/meson.build b/src/numcodecs/meson.build index 41a3a7a2..019b81db 100644 --- a/src/numcodecs/meson.build +++ b/src/numcodecs/meson.build @@ -286,5 +286,14 @@ py.install_sources( 'zarr3.py', 'zfpy.py', 'zlib.py', + # type stubs for the Cython extension modules + '_shuffle.pyi', + 'blosc.pyi', + 'compat_ext.pyi', + 'fletcher32.pyi', + 'jenkins.pyi', + 'lz4.pyi', + 'vlen.pyi', + 'zstd.pyi', subdir: 'numcodecs', ) diff --git a/src/numcodecs/ndarray_like.py b/src/numcodecs/ndarray_like.py index 06e15ea9..be4171bd 100644 --- a/src/numcodecs/ndarray_like.py +++ b/src/numcodecs/ndarray_like.py @@ -1,4 +1,12 @@ -from typing import Any, ClassVar, Protocol, runtime_checkable +from collections.abc import Buffer +from typing import Any, Protocol, Self, runtime_checkable + +from typing_extensions import TypeIs # in `typing` from Python 3.13 + +# Kept at module level, not as an annotated attribute of the metaclass: a protocol class +# without annotations of its own would otherwise find the metaclass's `__annotations__`, and +# `runtime_checkable` would then require instances to have the cache as an attribute. +_instancecheck_cache: dict[tuple[type, type], bool] = {} class _CachedProtocolMeta(Protocol.__class__): # type: ignore[name-defined] @@ -11,55 +19,89 @@ class _CachedProtocolMeta(Protocol.__class__): # type: ignore[name-defined] isinstance checks using the object's class as the cache key. """ - _instancecheck_cache: ClassVar[dict[tuple[type, type], bool]] = {} - - def __instancecheck__(self, instance): + def __instancecheck__(self, instance: object) -> bool: key = (self, instance.__class__) - ret = self._instancecheck_cache.get(key) + ret = _instancecheck_cache.get(key) if ret is None: ret = super().__instancecheck__(instance) - self._instancecheck_cache[key] = ret + _instancecheck_cache[key] = ret return ret +# The protocols below declare their attributes as read-only properties. numpy (and cupy) +# expose `dtype`, `shape`, `flags` and friends as read-only properties, and a protocol that +# declared them as plain (settable) attributes would not match a real ndarray. + + @runtime_checkable class DType(Protocol, metaclass=_CachedProtocolMeta): - itemsize: int - name: str - kind: str + @property + def itemsize(self) -> int: ... # pragma: no cover + @property + def name(self) -> str: ... # pragma: no cover + @property + def kind(self) -> str: ... # pragma: no cover + @property + def str(self) -> str: ... # pragma: no cover @runtime_checkable class FlagsObj(Protocol, metaclass=_CachedProtocolMeta): - c_contiguous: bool - f_contiguous: bool - owndata: bool + @property + def c_contiguous(self) -> bool: ... # pragma: no cover + @property + def f_contiguous(self) -> bool: ... # pragma: no cover + @property + def owndata(self) -> bool: ... # pragma: no cover @runtime_checkable class NDArrayLike(Protocol, metaclass=_CachedProtocolMeta): - dtype: DType - shape: tuple[int, ...] - strides: tuple[int, ...] - ndim: int - size: int - itemsize: int - nbytes: int - flags: FlagsObj + """The part of the ndarray interface numcodecs relies on. + + `numpy.ndarray` and `cupy.ndarray` both satisfy it. Methods return `Any` because numpy + overloads them heavily; convert with `numcodecs.compat.ensure_ndarray` when you need + numpy's own types. + """ + + @property + def dtype(self) -> DType: ... # pragma: no cover + @property + def shape(self) -> tuple[int, ...]: ... # pragma: no cover + @property + def strides(self) -> tuple[int, ...]: ... # pragma: no cover + @property + def ndim(self) -> int: ... # pragma: no cover + @property + def size(self) -> int: ... # pragma: no cover + @property + def itemsize(self) -> int: ... # pragma: no cover + @property + def nbytes(self) -> int: ... # pragma: no cover + @property + def flags(self) -> FlagsObj: ... # pragma: no cover def __len__(self) -> int: ... # pragma: no cover - def __getitem__(self, key) -> Any: ... # pragma: no cover + def __getitem__(self, key: Any, /) -> Any: ... # pragma: no cover + + def __setitem__(self, key: Any, value: Any, /) -> None: ... # pragma: no cover + + def tobytes(self, order: Any = ...) -> bytes: ... # pragma: no cover + + def reshape(self, *args: Any, **kwargs: Any) -> Any: ... # pragma: no cover - def __setitem__(self, key, value): ... # pragma: no cover + def view(self, *args: Any, **kwargs: Any) -> Any: ... # pragma: no cover - def tobytes(self, order: str | None = ...) -> bytes: ... # pragma: no cover + def copy(self, *args: Any, **kwargs: Any) -> Self: ... # pragma: no cover - def reshape(self, *shape: int, order: str = ...) -> "NDArrayLike": ... # pragma: no cover - def view(self, dtype: DType = ...) -> "NDArrayLike": ... # pragma: no cover +type BufferLike = Buffer | NDArrayLike +"""What codecs accept and return: an object exporting the buffer protocol (PEP 688), such +as `bytes`, `bytearray`, `memoryview` or a numpy array, or an ndarray-like such as a cupy +array.""" -def is_ndarray_like(obj: object) -> bool: +def is_ndarray_like(obj: object) -> TypeIs[NDArrayLike]: """Return True when `obj` is ndarray-like""" return isinstance(obj, NDArrayLike) diff --git a/src/numcodecs/registry.py b/src/numcodecs/registry.py index ccb5b26b..fa2a5f59 100644 --- a/src/numcodecs/registry.py +++ b/src/numcodecs/registry.py @@ -2,17 +2,22 @@ applications to dynamically register and look-up codec classes.""" import logging -from importlib.metadata import EntryPoints, entry_points +import warnings +from collections.abc import Mapping +from importlib.metadata import EntryPoint, entry_points +from typing import Any from numcodecs.abc import Codec from numcodecs.errors import UnknownCodecError logger = logging.getLogger("numcodecs") -codec_registry: dict[str, Codec] = {} -entries: dict[str, EntryPoints] = {} +codec_registry: dict[str, type[Codec]] = {} +"""Codec classes by codec id.""" +entries: dict[str, EntryPoint] = {} +"""Not-yet-loaded codec classes from the `numcodecs.codecs` entry point group, by codec id.""" -def run_entrypoints(): +def run_entrypoints() -> None: entries.clear() eps = entry_points() entries.update({e.name: e for e in eps.select(group="numcodecs.codecs")}) @@ -21,7 +26,7 @@ def run_entrypoints(): run_entrypoints() -def get_codec(config): +def get_codec(config: Mapping[str, Any]) -> Codec: """Obtain a codec for the given configuration. Parameters @@ -44,17 +49,25 @@ def get_codec(config): """ config = dict(config) codec_id = config.pop('id', None) - cls = codec_registry.get(codec_id) + cls = codec_registry.get(codec_id) if isinstance(codec_id, str) else None if cls is None and codec_id in entries: logger.debug("Auto loading codec '%s' from entrypoint", codec_id) cls = entries[codec_id].load() + if not (isinstance(cls, type) and issubclass(cls, Codec)): + warnings.warn( + f"The entry point for codec {codec_id!r} loads {cls!r}, which is not a " + "subclass of numcodecs.abc.Codec. Support for such codecs is deprecated " + "and will be removed in a future release.", + DeprecationWarning, + stacklevel=2, + ) register_codec(cls, codec_id=codec_id) if cls: return cls.from_config(config) raise UnknownCodecError(f"{codec_id!r}") -def register_codec(cls, codec_id=None): +def register_codec(cls: type[Codec], codec_id: str | None = None) -> None: """Register a codec class. Parameters @@ -69,6 +82,8 @@ def register_codec(cls, codec_id=None): """ if codec_id is None: - codec_id = cls.codec_id + codec_id = getattr(cls, "codec_id", None) + if codec_id is None: + raise ValueError(f"cannot register {cls!r}: it has no codec_id and none was given") logger.debug("Registering codec '%s'", codec_id) codec_registry[codec_id] = cls diff --git a/src/numcodecs/vlen.pyi b/src/numcodecs/vlen.pyi new file mode 100644 index 00000000..a4443000 --- /dev/null +++ b/src/numcodecs/vlen.pyi @@ -0,0 +1,41 @@ +from collections.abc import Iterable +from typing import Any, overload + +import numpy as np +import numpy.typing as npt + +from .abc import Codec +from .ndarray_like import BufferLike + +def check_out_param(out: npt.NDArray[np.object_], n_items: int) -> npt.NDArray[np.object_]: ... + +# VLenUTF8 and VLenBytes also accept a list (or other iterable) of str or bytes. VLenArray +# needs an object array: numpy would turn a list of equal-length arrays into a 2-D array. + +class VLenUTF8(Codec): + codec_id: str + def __init__(self) -> None: ... + def encode(self, buf: BufferLike | Iterable[str]) -> bytearray: ... + @overload + def decode(self, buf: BufferLike, out: None = None) -> npt.NDArray[np.object_]: ... + @overload + def decode[OutT: BufferLike](self, buf: BufferLike, out: OutT) -> OutT: ... + +class VLenBytes(Codec): + codec_id: str + def __init__(self) -> None: ... + def encode(self, buf: BufferLike | Iterable[bytes]) -> bytearray: ... + @overload + def decode(self, buf: BufferLike, out: None = None) -> npt.NDArray[np.object_]: ... + @overload + def decode[OutT: BufferLike](self, buf: BufferLike, out: OutT) -> OutT: ... + +class VLenArray(Codec): + codec_id: str + dtype: np.dtype[Any] + def __init__(self, dtype: npt.DTypeLike) -> None: ... + def encode(self, buf: BufferLike) -> bytearray: ... + @overload + def decode(self, buf: BufferLike, out: None = None) -> npt.NDArray[np.object_]: ... + @overload + def decode[OutT: BufferLike](self, buf: BufferLike, out: OutT) -> OutT: ... diff --git a/src/numcodecs/zstd.pyi b/src/numcodecs/zstd.pyi new file mode 100644 index 00000000..617e31f2 --- /dev/null +++ b/src/numcodecs/zstd.pyi @@ -0,0 +1,35 @@ +from typing import Final, overload + +from .abc import Codec +from .ndarray_like import BufferLike + +VERSION_NUMBER: Final[int] +MAJOR_VERSION_NUMBER: Final[int] +MINOR_VERSION_NUMBER: Final[int] +MICRO_VERSION_NUMBER: Final[int] +DEFAULT_CLEVEL: Final[int] +MAX_CLEVEL: Final[int] + +def compress(source: BufferLike, level: int = ..., checksum: bool = False) -> bytes: ... +@overload +def decompress(source: BufferLike, dest: None = None) -> bytes: ... +@overload +def decompress[OutT: BufferLike](source: BufferLike, dest: OutT) -> OutT: ... + +class Zstd(Codec): + codec_id: str + max_buffer_size: int + level: int + checksum: bool + def __init__(self, level: int = ..., checksum: bool = False) -> None: ... + def encode(self, buf: BufferLike) -> bytes: ... + @overload + def decode(self, buf: BufferLike, out: None = None) -> bytes: ... + @overload + def decode[OutT: BufferLike](self, buf: BufferLike, out: OutT) -> OutT: ... + @classmethod + def default_level(cls) -> int: ... + @classmethod + def min_level(cls) -> int: ... + @classmethod + def max_level(cls) -> int: ... diff --git a/tests/test_blosc.py b/tests/test_blosc.py index b920f03e..abff0592 100644 --- a/tests/test_blosc.py +++ b/tests/test_blosc.py @@ -7,9 +7,8 @@ import pytest try: - from numcodecs.blosc import Blosc - from numcodecs import blosc + from numcodecs.blosc import Blosc except ImportError: # pragma: no cover pytest.skip("numcodecs.blosc not available", allow_module_level=True) diff --git a/tests/test_codec_contract.py b/tests/test_codec_contract.py index bf47cc00..5d871c00 100644 --- a/tests/test_codec_contract.py +++ b/tests/test_codec_contract.py @@ -21,6 +21,7 @@ import numcodecs from numcodecs import pickles from numcodecs.abc import Codec +from numcodecs.compat import ensure_ndarray @dataclass(frozen=True) @@ -147,9 +148,9 @@ def test_decode_into_ndarray_returns_out(codec_id: str) -> None: out = np.empty_like(data) assert codec.decode(enc, out=out) is out if CASES[codec_id].is_object: - assert all(np.array_equal(a, b) for a, b in zip(out, expected, strict=True)) + assert all(np.array_equal(a, b) for a, b in zip(out, ensure_ndarray(expected), strict=True)) else: - assert np.asarray(memoryview(expected)).tobytes() == out.tobytes() + assert ensure_ndarray(expected).tobytes() == out.tobytes() @pytest.mark.parametrize( @@ -161,7 +162,7 @@ def test_decode_into_bytearray_returns_out(codec_id: str) -> None: expected = codec.decode(enc) out = bytearray(data.nbytes) assert codec.decode(enc, out=out) is out - assert bytes(out) == np.asarray(memoryview(expected)).tobytes() + assert bytes(out) == ensure_ndarray(expected).tobytes() @pytest.mark.parametrize("codec_id", _params(set())) diff --git a/tests/test_fletcher32.py b/tests/test_fletcher32.py index adfb31da..3bbefe85 100644 --- a/tests/test_fletcher32.py +++ b/tests/test_fletcher32.py @@ -1,5 +1,6 @@ import numpy as np import pytest + from numcodecs.fletcher32 import Fletcher32 diff --git a/tests/test_jenkins.py b/tests/test_jenkins.py index 511c435c..ae4cd055 100644 --- a/tests/test_jenkins.py +++ b/tests/test_jenkins.py @@ -1,8 +1,8 @@ import numpy as np import pytest -from numcodecs.jenkins import jenkins_lookup3 from numcodecs.checksum32 import JenkinsLookup3 +from numcodecs.jenkins import jenkins_lookup3 def test_jenkins_lookup3(): diff --git a/tests/test_registry.py b/tests/test_registry.py index 93ed8f03..ea44ea10 100644 --- a/tests/test_registry.py +++ b/tests/test_registry.py @@ -1,4 +1,5 @@ import inspect +import types import pytest @@ -34,10 +35,43 @@ def test_all_classes_registered(): if ( inspect.isclass(obj) and issubclass(obj, numcodecs.abc.Codec) + and not inspect.isabstract(obj) and obj.codec_id not in numcodecs.registry.codec_registry - and obj.codec_id is not None # remove `None` ) } if missing: raise Exception(f"these codecs are missing: {missing}") # pragma: no cover + + +class _DuckCodec: + """Looks like a codec, but does not subclass numcodecs.abc.Codec.""" + + codec_id = "duck" + + @classmethod + def from_config(cls, config): + return cls() + + +def test_entry_point_not_a_codec_subclass_is_deprecated(monkeypatch): + monkeypatch.setitem( + numcodecs.registry.entries, "duck", types.SimpleNamespace(load=lambda: _DuckCodec) + ) + monkeypatch.delitem(numcodecs.registry.codec_registry, "duck", raising=False) + with pytest.warns(DeprecationWarning, match="not a subclass of numcodecs.abc.Codec"): + codec = get_codec({"id": "duck"}) + assert isinstance(codec, _DuckCodec) + numcodecs.registry.codec_registry.pop("duck") + + +def test_register_codec_without_id(): + class NoId(numcodecs.abc.Codec): + def encode(self, buf): # pragma: no cover + return buf + + def decode(self, buf, out=None): # pragma: no cover + return buf + + with pytest.raises(ValueError, match="has no codec_id and none was given"): + numcodecs.register_codec(NoId) diff --git a/tests/test_zstd.py b/tests/test_zstd.py index 04f82383..b47363c7 100644 --- a/tests/test_zstd.py +++ b/tests/test_zstd.py @@ -3,8 +3,8 @@ import numpy as np import pytest -from numcodecs.zstd import Zstd +from numcodecs.zstd import Zstd from tests.common import ( check_backwards_compatibility, check_config, diff --git a/tests/typing/README.md b/tests/typing/README.md index a885a096..c9f32fcf 100644 --- a/tests/typing/README.md +++ b/tests/typing/README.md @@ -21,5 +21,16 @@ configuration in `pyproject.toml` covers those. `pyrightconfig.json` turns off pyright's three `reportUnknown*` rules, because most numcodecs parameters are not annotated yet. Turn them back on once they are. +The Cython extension modules carry their types in `.pyi` stubs next to the `.pyx` sources. +`mypy.stubtest` compares those stubs with the compiled modules, against an installed +(non-editable) build: + +```bash +MYPYPATH=src python -m mypy.stubtest --mypy-config-file pyproject.toml \ + --allowlist tests/typing/stubtest-allowlist.txt \ + numcodecs.blosc numcodecs.zstd numcodecs.lz4 numcodecs.vlen \ + numcodecs.fletcher32 numcodecs.jenkins numcodecs.compat_ext numcodecs._shuffle +``` + When you change an annotation in numcodecs, add or update an `assert_type` here that shows what callers now get. diff --git a/tests/typing/mypy.ini b/tests/typing/mypy.ini index 26579ad7..0159ab2f 100644 --- a/tests/typing/mypy.ini +++ b/tests/typing/mypy.ini @@ -2,6 +2,8 @@ # Run from the repository root: `mypy --config-file tests/typing/mypy.ini tests/typing` [mypy] strict = true +# the oldest supported Python, so names that only exist in newer `typing` modules are caught +python_version = 3.12 warn_unreachable = true enable_error_code = ignore-without-code, redundant-expr, truthy-bool # Read numcodecs from the source tree. It does not ship a py.typed marker yet, so mypy diff --git a/tests/typing/pyrightconfig.json b/tests/typing/pyrightconfig.json index 42540aad..fac5363b 100644 --- a/tests/typing/pyrightconfig.json +++ b/tests/typing/pyrightconfig.json @@ -10,5 +10,6 @@ "reportMissingTypeStubs": "none", "reportUnknownVariableType": "none", "reportUnknownMemberType": "none", - "reportUnknownArgumentType": "none" + "reportUnknownArgumentType": "none", + "reportMissingModuleSource": "none" } diff --git a/tests/typing/stubtest-allowlist.txt b/tests/typing/stubtest-allowlist.txt new file mode 100644 index 00000000..39407367 --- /dev/null +++ b/tests/typing/stubtest-allowlist.txt @@ -0,0 +1,10 @@ +# Entries for `python -m mypy.stubtest`, one regular expression per line. + +# Cython adds a `__test__` dict (collected doctests) to every module. +numcodecs\..*\.__test__ + +# Cython reports `def f():` module functions as `(self, /)` at runtime. +numcodecs\.blosc\.(_init|_destroy|_get_use_threads|get_nthreads|list_compressors) + +# Cython's C-API capsule table for cimport-able functions. +numcodecs\.compat_ext\.__pyx_capi__ diff --git a/tests/typing/test_abc_types.py b/tests/typing/test_abc_types.py new file mode 100644 index 00000000..ababbebb --- /dev/null +++ b/tests/typing/test_abc_types.py @@ -0,0 +1,92 @@ +"""Static types of `numcodecs.abc`, checked against runtime behavior.""" + +from collections.abc import Mapping +from typing import Any, Self, assert_type, overload + +import numpy as np +import numpy.typing as npt + +import numcodecs +from numcodecs.abc import Codec, CodecProtocol +from numcodecs.compat import ensure_bytes, ndarray_copy +from numcodecs.ndarray_like import BufferLike + + +def _zlib() -> Codec: + return numcodecs.get_codec({"id": "zlib", "level": 1}) + + +def test_codec_methods() -> None: + codec = _zlib() + data = np.arange(16, dtype="f8") + + assert_type(codec.codec_id, str) + assert codec.codec_id == "zlib" + + enc = assert_type(codec.encode(data), BufferLike) + dec = assert_type(codec.decode(enc), BufferLike) + assert ensure_bytes(dec) == data.tobytes() + + out: npt.NDArray[np.float64] = np.empty_like(data) + assert assert_type(codec.decode(enc, out=out), npt.NDArray[np.float64]) is out + buf = bytearray(data.nbytes) + assert assert_type(codec.decode(enc, out=buf), bytearray) is buf + + config = assert_type(codec.get_config(), Mapping[str, Any]) + assert config["id"] == "zlib" + rebuilt = assert_type(type(codec).from_config({"level": 1}), Codec) + assert rebuilt == codec + + assert_type(codec == object(), bool) + + +def test_codec_satisfies_codec_protocol() -> None: + codec: CodecProtocol = _zlib() + assert codec.codec_id == "zlib" + + +class _Identity(Codec): + """A third-party codec typed as precisely as numcodecs' own.""" + + codec_id = "test-identity" + + def encode(self, buf: BufferLike, /) -> bytes: + return ensure_bytes(buf) + + @overload + def decode(self, buf: BufferLike, /, out: None = None) -> bytes: ... + @overload + def decode[OutT: BufferLike](self, buf: BufferLike, /, out: OutT) -> OutT: ... + def decode(self, buf: BufferLike, /, out: BufferLike | None = None) -> BufferLike: + return ndarray_copy(ensure_bytes(buf), out) + + +class _AnyTyped(Codec): + """A third-party codec annotated with `Any`, as imagecodecs does.""" + + codec_id = "test-any" + + def encode(self, buf: Any) -> Any: + return buf + + def decode(self, buf: Any, out: Any = None) -> Any: + return buf + + def get_config(self) -> dict[str, Any]: + return {"id": self.codec_id} + + @classmethod + def from_config(cls, config: Mapping[str, Any]) -> Self: + return cls() + + +def test_subclasses() -> None: + identity = _Identity() + assert assert_type(identity.encode(b"abc"), bytes) == b"abc" + assert assert_type(identity.decode(b"abc"), bytes) == b"abc" + out = bytearray(3) + assert assert_type(identity.decode(b"abc", out=out), bytearray) is out + + any_typed = _AnyTyped() + assert any_typed.decode(any_typed.encode(b"abc")) == b"abc" + assert_type(_AnyTyped.from_config({}), _AnyTyped) diff --git a/tests/typing/test_compat_types.py b/tests/typing/test_compat_types.py index f656c411..e8a5bac1 100644 --- a/tests/typing/test_compat_types.py +++ b/tests/typing/test_compat_types.py @@ -10,7 +10,24 @@ import numpy as np import numpy.typing as npt -from numcodecs.compat import ensure_bytes, ensure_contiguous_ndarray, ensure_ndarray +from numcodecs.compat import ( + ensure_bytes, + ensure_contiguous_ndarray, + ensure_ndarray, + ensure_ndarray_like, + ensure_text, + ndarray_copy, +) +from numcodecs.ndarray_like import NDArrayLike, is_ndarray_like + + +def _as_ndarray_like(x: NDArrayLike) -> NDArrayLike: + """Forget the concrete type, as for an ndarray-like that is not a numpy array.""" + return x + + +def _as_object(x: object) -> object: + return x def test_ensure_bytes() -> None: @@ -29,3 +46,42 @@ def test_ensure_contiguous_ndarray() -> None: for buf in (b"abc", bytearray(b"abc"), memoryview(b"abc"), np.arange(3, dtype="u1")): result = assert_type(ensure_contiguous_ndarray(buf), npt.NDArray[Any]) assert isinstance(result, np.ndarray) + + +def test_ensure_ndarray_like() -> None: + from_bytes = assert_type(ensure_ndarray_like(b"abc"), npt.NDArray[Any]) + assert isinstance(from_bytes, np.ndarray) + # an ndarray-like that is not known to export the buffer protocol (such as a cupy array) + # comes back as the protocol type + like = _as_ndarray_like(np.arange(3)) + from_like = assert_type(ensure_ndarray_like(like), NDArrayLike) + assert from_like is like + + +def test_ensure_text() -> None: + for s in ("abc", b"abc", bytearray(b"abc"), memoryview(b"abc")): + result = assert_type(ensure_text(s), str) + assert result == "abc" + + +def test_ndarray_copy() -> None: + src = b"\x01\x02\x03" + # without a destination, the source comes back unchanged + same = assert_type(ndarray_copy(src, None), bytes) + assert same is src + # with a destination, that very object comes back, filled + dst = bytearray(3) + filled = assert_type(ndarray_copy(src, dst), bytearray) + assert filled is dst + assert bytes(dst) == src + arr: npt.NDArray[np.uint8] = np.zeros(3, dtype=np.uint8) + assert assert_type(ndarray_copy(src, arr), npt.NDArray[np.uint8]) is arr + + +def test_is_ndarray_like_narrows() -> None: + obj = _as_object(np.arange(3)) + if is_ndarray_like(obj): + assert_type(obj, NDArrayLike) + assert obj.shape == (3,) + else: # pragma: no cover + raise AssertionError diff --git a/tests/typing/test_cython_types.py b/tests/typing/test_cython_types.py new file mode 100644 index 00000000..ae2f3572 --- /dev/null +++ b/tests/typing/test_cython_types.py @@ -0,0 +1,59 @@ +"""Static types of the Cython codecs, as declared in their `.pyi` stubs, checked against +runtime behavior.""" + +from typing import assert_type + +import numpy as np +import numpy.typing as npt + +from numcodecs.blosc import Blosc +from numcodecs.fletcher32 import Fletcher32 +from numcodecs.jenkins import jenkins_lookup3 +from numcodecs.lz4 import LZ4 +from numcodecs.vlen import VLenArray, VLenBytes, VLenUTF8 +from numcodecs.zstd import Zstd + +DATA = np.arange(16, dtype="f8") + + +def test_compressors() -> None: + for codec in (Blosc(), Zstd(), LZ4()): + enc = assert_type(codec.encode(DATA), bytes) + assert isinstance(enc, bytes) + dec = assert_type(codec.decode(enc), bytes) + assert dec == DATA.tobytes() + out = bytearray(DATA.nbytes) + assert assert_type(codec.decode(enc, out=out), bytearray) is out + + +def test_zstd_levels() -> None: + for level in (Zstd.default_level(), Zstd.min_level(), Zstd.max_level()): + assert isinstance(assert_type(level, int), int) + + +def test_fletcher32() -> None: + codec = Fletcher32() + enc = assert_type(codec.encode(DATA), bytes) + dec = assert_type(codec.decode(enc), npt.NDArray[np.uint8]) + assert isinstance(dec, np.ndarray) + assert dec.tobytes() == DATA.tobytes() + + +def test_jenkins_lookup3() -> None: + assert isinstance(assert_type(jenkins_lookup3(b"abc"), int), int) + + +def test_vlen() -> None: + utf8 = VLenUTF8() + enc = assert_type(utf8.encode(["foo", "bar"]), bytearray) + dec = assert_type(utf8.decode(enc), npt.NDArray[np.object_]) + assert dec.tolist() == ["foo", "bar"] + + raw = VLenBytes() + assert raw.decode(assert_type(raw.encode([b"foo"]), bytearray)).tolist() == [b"foo"] + + arrays = VLenArray(dtype="i4") + values = np.empty(2, dtype=object) + values[0], values[1] = np.arange(3, dtype="i4"), np.arange(2, dtype="i4") + enc = assert_type(arrays.encode(values), bytearray) + assert assert_type(arrays.decode(enc), npt.NDArray[np.object_])[0].tolist() == [0, 1, 2] diff --git a/tests/typing/test_registry_types.py b/tests/typing/test_registry_types.py new file mode 100644 index 00000000..47a4b9a7 --- /dev/null +++ b/tests/typing/test_registry_types.py @@ -0,0 +1,26 @@ +"""Static types of `numcodecs.registry`, checked against runtime behavior.""" + +from importlib.metadata import EntryPoint +from typing import assert_type + +import numcodecs +from numcodecs.abc import Codec +from numcodecs.registry import codec_registry, entries, get_codec + + +def test_get_codec() -> None: + codec = assert_type(get_codec({"id": "zlib", "level": 1}), Codec) + assert isinstance(codec, numcodecs.Zlib) + + +def test_codec_registry_holds_classes() -> None: + assert_type(codec_registry, dict[str, type[Codec]]) + for cls in codec_registry.values(): + assert isinstance(cls, type) + assert issubclass(cls, Codec) + + +def test_entries_hold_entry_points() -> None: + assert_type(entries, dict[str, EntryPoint]) + for entry in entries.values(): + assert isinstance(entry, EntryPoint)