|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from typing import TYPE_CHECKING, Protocol, TypeVar, runtime_checkable |
| 4 | + |
| 5 | +if TYPE_CHECKING: |
| 6 | + from collections.abc import Iterator |
| 7 | + |
| 8 | +_T_co = TypeVar("_T_co", covariant=True) |
| 9 | + |
| 10 | + |
| 11 | +@runtime_checkable |
| 12 | +class NestedSequence(Protocol[_T_co]): |
| 13 | + """A protocol for representing nested sequences. |
| 14 | +
|
| 15 | + Warning: |
| 16 | + ------- |
| 17 | + `NestedSequence` currently does not work in combination with type variables, |
| 18 | + *e.g.* ``def func(a: NestedSequnce[T]) -> T: ...``. |
| 19 | +
|
| 20 | + See Also: |
| 21 | + -------- |
| 22 | + collections.abc.Sequence: |
| 23 | + ABCs for read-only and mutable :term:`sequences`. |
| 24 | +
|
| 25 | + Examples: |
| 26 | + -------- |
| 27 | + .. code-block:: python |
| 28 | +
|
| 29 | + >>> from typing import TYPE_CHECKING |
| 30 | + >>> import numpy as np |
| 31 | + >>> import array_api_typing as xpt |
| 32 | +
|
| 33 | + >>> def get_dtype(seq: xpt.NestedSequence[float]) -> np.dtype[np.float64]: |
| 34 | + ... return np.asarray(seq).dtype |
| 35 | +
|
| 36 | + >>> a = get_dtype([1.0]) |
| 37 | + >>> b = get_dtype([[1.0]]) |
| 38 | + >>> c = get_dtype([[[1.0]]]) |
| 39 | + >>> d = get_dtype([[[[1.0]]]]) |
| 40 | +
|
| 41 | + >>> if TYPE_CHECKING: |
| 42 | + ... reveal_locals() |
| 43 | + ... # note: Revealed local types are: |
| 44 | + ... # note: a: numpy.dtype[numpy.floating[numpy._typing._64Bit]] |
| 45 | + ... # note: b: numpy.dtype[numpy.floating[numpy._typing._64Bit]] |
| 46 | + ... # note: c: numpy.dtype[numpy.floating[numpy._typing._64Bit]] |
| 47 | + ... # note: d: numpy.dtype[numpy.floating[numpy._typing._64Bit]] |
| 48 | +
|
| 49 | + """ |
| 50 | + |
| 51 | + def __len__(self, /) -> int: |
| 52 | + """Implement ``len(self)``.""" |
| 53 | + raise NotImplementedError |
| 54 | + |
| 55 | + def __getitem__(self, index: int, /) -> _T_co | NestedSequence[_T_co]: |
| 56 | + """Implement ``self[x]``.""" |
| 57 | + raise NotImplementedError |
| 58 | + |
| 59 | + def __contains__(self, x: object, /) -> bool: |
| 60 | + """Implement ``x in self``.""" |
| 61 | + raise NotImplementedError |
| 62 | + |
| 63 | + def __iter__(self, /) -> Iterator[_T_co | NestedSequence[_T_co]]: |
| 64 | + """Implement ``iter(self)``.""" |
| 65 | + raise NotImplementedError |
| 66 | + |
| 67 | + def __reversed__(self, /) -> Iterator[_T_co | NestedSequence[_T_co]]: |
| 68 | + """Implement ``reversed(self)``.""" |
| 69 | + raise NotImplementedError |
| 70 | + |
| 71 | + def count(self, value: object, /) -> int: |
| 72 | + """Return the number of occurrences of `value`.""" |
| 73 | + raise NotImplementedError |
| 74 | + |
| 75 | + def index(self, value: object, /) -> int: |
| 76 | + """Return the first index of `value`.""" |
| 77 | + raise NotImplementedError |
0 commit comments