-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Mypy doesn't recognize a class as iterable when it implements only __getitem__
#2220
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
Comments
We should support this. It is part of the Python spec for
|
We currently require an explicit A better fix would require structural subtyping (or protocols), but that's going to be harder. And we'd need another special case for |
I ran into this problem with |
This is not really a mypy problem. If you ask Python at runtime class A:
def __iter__(self):
...
class B:
def __getitem__(self):
...
isinstance(A(), collections.abc.Iterable) # True
isinstance(B(), collections.abc.Iterable) # False There were long discussions about this but there is still no decision about this. If you control the expected type you can define your own protocol: class OtherIterable(Protocol[T]):
def __getitem__(self, index: int) -> T:
...
WideIterable = Union[Iterable[T], OtherIterable[T]]
def fun(arg: WideIterable[str]) -> None:
...
class One:
def __iter__(self) -> Iterator[str]:
...
class Other:
def __getitem__(self, index: int) -> str:
...
fun(One()) # OK
fun(Other()) # OK or whatever else you want. |
So what's the solution for for pattern in sre_parse.parse('(\w+)(\d+)'):
print(pattern) Mypy prints:
|
We should probably just lie in the stubs for sre_parse and claim that SubPattern is Iterable. |
Same problem for Exceptions in Python2: d = {0: 0}
try:
d[1]
except KeyError as ex:
(key,) = ex
# error: 'builtins.KeyError' object is not iterable I can work-around that by explicitly accessing |
Has there been any progress on this issue? |
This problem still appears to exist in version 0.790. Specifically, the Edit: turns out I had an unrelated type error that was causing this problem, never mind me! |
Any solution or workaround to this? I get the same error. I don't want to ignore these errors by |
For for x in subpattern:
... to for x in subpattern.data:
... not really ideal since it accesses a field that is probably intended to be private/internal, but it works. |
There was some more recent discussion in python/typeshed#7813 The outcome is python/typeshed#7817 , which gives a not terrible workaround — just add an
If you maintain an iterable class, just add an
|
This comment was marked as resolved.
This comment was marked as resolved.
I just ran into this issue. In my case, I have control over the class, so I added an
In my case
I don't how python actually implements this, so there might be other cases which are not covered. |
The following code runs fine, but mypy produce an error:
The text was updated successfully, but these errors were encountered: