_nested_sequence.py 2.5 KB

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