_nested_sequence.py 2.6 KB

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