-
-
Notifications
You must be signed in to change notification settings - Fork 10.8k
ENH: Add a typing protocol for representing nested sequences #19894
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
"""A module containing the `_NestedSequence` protocol.""" | ||
|
||
from __future__ import annotations | ||
|
||
import sys | ||
from typing import ( | ||
Any, | ||
Iterator, | ||
overload, | ||
TypeVar, | ||
Protocol, | ||
) | ||
|
||
__all__ = ["_NestedSequence"] | ||
|
||
_T_co = TypeVar("_T_co", covariant=True) | ||
|
||
|
||
class _NestedSequence(Protocol[_T_co]): | ||
"""A protocol for representing nested sequences. | ||
|
||
Warning | ||
------- | ||
`_NestedSequence` currently does not work in combination with typevars, | ||
*e.g.* ``def func(a: _NestedSequnce[T]) -> T: ...``. | ||
|
||
See Also | ||
-------- | ||
`collections.abc.Sequence` | ||
ABCs for read-only and mutable :term:`sequences`. | ||
|
||
Examples | ||
-------- | ||
.. code-block:: python | ||
|
||
>>> from __future__ import annotations | ||
|
||
>>> from typing import TYPE_CHECKING | ||
>>> import numpy as np | ||
>>> from numpy.typing import _NestedSequnce | ||
|
||
>>> def get_dtype(seq: _NestedSequnce[float]) -> np.dtype[np.float64]: | ||
... return np.asarray(seq).dtype | ||
|
||
>>> a = get_dtype([1.0]) | ||
>>> b = get_dtype([[1.0]]) | ||
>>> c = get_dtype([[[1.0]]]) | ||
>>> d = get_dtype([[[[1.0]]]]) | ||
|
||
>>> if TYPE_CHECKING: | ||
... reveal_locals() | ||
... # note: Revealed local types are: | ||
... # note: a: numpy.dtype[numpy.floating[numpy.typing._64Bit]] | ||
... # note: b: numpy.dtype[numpy.floating[numpy.typing._64Bit]] | ||
... # note: c: numpy.dtype[numpy.floating[numpy.typing._64Bit]] | ||
... # note: d: numpy.dtype[numpy.floating[numpy.typing._64Bit]] | ||
|
||
""" | ||
|
||
def __len__(self, /) -> int: | ||
"""Implement ``len(self)``.""" | ||
raise NotImplementedError | ||
|
||
@overload | ||
def __getitem__(self, index: int, /) -> _T_co | _NestedSequence[_T_co]: ... | ||
@overload | ||
def __getitem__(self, index: slice, /) -> _NestedSequence[_T_co]: ... | ||
|
||
def __getitem__(self, index, /): | ||
"""Implement ``self[x]``.""" | ||
raise NotImplementedError | ||
|
||
def __contains__(self, x: object, /) -> bool: | ||
"""Implement ``x in self``.""" | ||
raise NotImplementedError | ||
|
||
def __iter__(self, /) -> Iterator[_T_co | _NestedSequence[_T_co]]: | ||
"""Implement ``iter(self)``.""" | ||
raise NotImplementedError | ||
|
||
def __reversed__(self, /) -> Iterator[_T_co | _NestedSequence[_T_co]]: | ||
"""Implement ``reversed(self)``.""" | ||
raise NotImplementedError | ||
|
||
def count(self, value: Any, /) -> int: | ||
"""Return the number of occurrences of `value`.""" | ||
raise NotImplementedError | ||
|
||
def index( | ||
self, value: Any, start: int = 0, stop: int = sys.maxsize, / | ||
) -> int: | ||
"""Return the first index of `value`.""" | ||
raise NotImplementedError |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
from typing import Sequence, Tuple, List | ||
import numpy.typing as npt | ||
|
||
a: Sequence[float] | ||
b: List[complex] | ||
c: Tuple[str, ...] | ||
d: int | ||
e: str | ||
|
||
def func(a: npt._NestedSequence[int]) -> None: | ||
... | ||
|
||
reveal_type(func(a)) # E: incompatible type | ||
reveal_type(func(b)) # E: incompatible type | ||
reveal_type(func(c)) # E: incompatible type | ||
reveal_type(func(d)) # E: incompatible type | ||
reveal_type(func(e)) # E: incompatible type |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is used with typevars in
def func(a: _ArrayLike[_T]) -> NDArray[_T]: ...
-esque expressions, so unfortunately we can't use the new fancy protocol here.