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