Skip to content

Mypy treats types with __getitem__ as not iterables #11695

Closed
@sobolevn

Description

@sobolevn

Sample:

class Some:
    def __getitem__(self, i: int) -> str:
        if i >= 2:
            raise IndexError()
        return chr(97 + i)

s = Some()
for x in s:  # error here
    print(x)

Output:

» mypy out/ex.py --strict-optional --warn-unreachable --show-traceback
out/ex.py:10: error: "Some" has no attribute "__iter__" (not iterable)

But, in runtime it works just fine:

» python out/ex.py
a
b

Docs: https://pyneng.readthedocs.io/en/latest/book/23_oop_special_methods/iterable_iterator.html#iteration-protocol

I will try to send a PR soon!

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions