|
1 | | -from typing import Any, ClassVar, Protocol, runtime_checkable |
2 | | - |
3 | | - |
4 | | -class _CachedProtocolMeta(Protocol.__class__): # type: ignore[name-defined] |
5 | | - """Custom implementation of @runtime_checkable |
6 | | -
|
7 | | - The native implementation of @runtime_checkable is slow, |
8 | | - see <https://github.com/zarr-developers/numcodecs/issues/379>. |
9 | | -
|
10 | | - This metaclass keeps an unbounded cache of the result of |
11 | | - isinstance checks using the object's class as the cache key. |
12 | | - """ |
13 | | - |
14 | | - _instancecheck_cache: ClassVar[dict[tuple[type, type], bool]] = {} |
15 | | - |
16 | | - def __instancecheck__(self, instance): |
17 | | - key = (self, instance.__class__) |
18 | | - ret = self._instancecheck_cache.get(key) |
19 | | - if ret is None: |
20 | | - ret = super().__instancecheck__(instance) |
21 | | - self._instancecheck_cache[key] = ret |
22 | | - return ret |
23 | | - |
24 | | - |
25 | | -@runtime_checkable |
26 | | -class DType(Protocol, metaclass=_CachedProtocolMeta): |
27 | | - itemsize: int |
28 | | - name: str |
29 | | - kind: str |
30 | | - |
31 | | - |
32 | | -@runtime_checkable |
33 | | -class FlagsObj(Protocol, metaclass=_CachedProtocolMeta): |
34 | | - c_contiguous: bool |
35 | | - f_contiguous: bool |
36 | | - owndata: bool |
37 | | - |
38 | | - |
39 | | -@runtime_checkable |
40 | | -class NDArrayLike(Protocol, metaclass=_CachedProtocolMeta): |
41 | | - dtype: DType |
42 | | - shape: tuple[int, ...] |
43 | | - strides: tuple[int, ...] |
44 | | - ndim: int |
45 | | - size: int |
46 | | - itemsize: int |
47 | | - nbytes: int |
48 | | - flags: FlagsObj |
49 | | - |
50 | | - def __len__(self) -> int: ... # pragma: no cover |
51 | | - |
52 | | - def __getitem__(self, key) -> Any: ... # pragma: no cover |
53 | | - |
54 | | - def __setitem__(self, key, value): ... # pragma: no cover |
55 | | - |
56 | | - def tobytes(self, order: str | None = ...) -> bytes: ... # pragma: no cover |
57 | | - |
58 | | - def reshape(self, *shape: int, order: str = ...) -> "NDArrayLike": ... # pragma: no cover |
59 | | - |
60 | | - def view(self, dtype: DType = ...) -> "NDArrayLike": ... # pragma: no cover |
| 1 | +import numpy.typing as npt |
61 | 2 |
|
62 | 3 |
|
63 | 4 | def is_ndarray_like(obj: object) -> bool: |
64 | 5 | """Return True when `obj` is ndarray-like""" |
65 | | - return isinstance(obj, NDArrayLike) |
| 6 | + return isinstance(obj, npt.ArrayLike) |
0 commit comments