1"""A module containing the `_NestedSequence` protocol."""
2
3from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
4
5if TYPE_CHECKING:
6 from collections.abc import Iterator
7 from typing_extensions import TypeVar
8
9 _T_co = TypeVar("_T_co", covariant=True, default=Any)
10else:
11 from typing import TypeVar
12
13 _T_co = TypeVar("_T_co", covariant=True)
14
15
16__all__ = ["_NestedSequence"]
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 typing import TYPE_CHECKING
38 >>> import numpy as np
39 >>> from numpy._typing import _NestedSequence
40
41 >>> def get_dtype(seq: _NestedSequence[float]) -> np.dtype[np.float64]:
42 ... return np.asarray(seq).dtype
43
44 >>> a = get_dtype([1.0])
45 >>> b = get_dtype([[1.0]])
46 >>> c = get_dtype([[[1.0]]])
47 >>> d = get_dtype([[[[1.0]]]])
48
49 >>> if TYPE_CHECKING:
50 ... reveal_locals()
51 ... # note: Revealed local types are:
52 ... # note: a: numpy.dtype[numpy.floating[numpy._typing._64Bit]]
53 ... # note: b: numpy.dtype[numpy.floating[numpy._typing._64Bit]]
54 ... # note: c: numpy.dtype[numpy.floating[numpy._typing._64Bit]]
55 ... # note: d: numpy.dtype[numpy.floating[numpy._typing._64Bit]]
56
57 """
58
59 def __len__(self, /) -> int:
60 """Implement ``len(self)``."""
61 raise NotImplementedError
62
63 def __getitem__(self, index: int, /) -> "_T_co | _NestedSequence[_T_co]":
64 """Implement ``self[x]``."""
65 raise NotImplementedError
66
67 def __contains__(self, x: object, /) -> bool:
68 """Implement ``x in self``."""
69 raise NotImplementedError
70
71 def __iter__(self, /) -> "Iterator[_T_co | _NestedSequence[_T_co]]":
72 """Implement ``iter(self)``."""
73 raise NotImplementedError
74
75 def __reversed__(self, /) -> "Iterator[_T_co | _NestedSequence[_T_co]]":
76 """Implement ``reversed(self)``."""
77 raise NotImplementedError
78
79 def count(self, value: Any, /) -> int:
80 """Return the number of occurrences of `value`."""
81 raise NotImplementedError
82
83 def index(self, value: Any, /) -> int:
84 """Return the first index of `value`."""
85 raise NotImplementedError