Mypy doesn't recognize a class as iterable when it implements only `__getitem__`

Open
#2,220 14 comments 16 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
35/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Stale
Tech stack
python
Domain
devtools

Research direction

Start with the reproducer in example.py and investigate how mypy handles iterable classes that define only getitem. Compare the reported list(Foo()) error with the relevant typing behavior; done means mypy accepts the example without the overload error.

Written by the indexing model from the issue text.

Description

feature priority-1-normal

The following code runs fine, but mypy produce an error:

from typing import List

class Foo(object):
    def __init__(self):
        self.version = [1, 2, 3]

    def __getitem__(self, k):
        return self.version[k]


def list_foo(f):
    # type: (Foo) -> List[int]
    return list(f)

print list_foo(Foo())
example.py: note: In function "list_foo":
example.py:13: error: No overload variant of "list" matches argument types [example.Foo]
Fail
Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.