Nested sequence type fails to detect errors #1145
Unanswered
charbonnierg
asked this question in
Q&A
Replies: 1 comment
-
Minimal reproducer: from __future__ import annotations
from typing import Iterator, overload, TypeVar, Protocol
_T_co = TypeVar("_T_co", covariant=True)
class _NestedSequence(Protocol[_T_co]):
def __len__(self, /) -> int: ...
@overload
def __getitem__(self, index: int, /) -> _T_co | _NestedSequence[_T_co]: ...
@overload
def __getitem__(self, index: slice, /) -> _NestedSequence[_T_co]: ...
def __iter__(self, /) -> Iterator[_T_co | _NestedSequence[_T_co]]: ...
def __reversed__(self, /) -> Iterator[_T_co | _NestedSequence[_T_co]]: ...
def foo(x: _NestedSequence[int]) -> None:
pass
foo(["lol"]) # no error This appears to be a bug in mypy. With pyright, I get an error from |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
A solution has been proposed by @BvB93 in python/mypy#731 (comment) to implement nested sequence type using
Protocol
.This solution is used by
numpy._typing._nested_sequence._NestedSequence
.When a function argument is annotated as
_NestedSequence[int]
, mypy does not raise errors when literal values are used:I tried to look for more information on github issues or google, but could not find whether this is a known limitation or not, or what would explain this behavior.
If someone can share some thoughts it would be much appreciated !
Thanks
Beta Was this translation helpful? Give feedback.
All reactions