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