mypy: Signature of “__getitem__” incompatible with supertype “Sequence”

白昼怎懂夜的黑 提交于 2019-12-23 09:40:34

问题


I have a class that inherits from MutableSequence like this:

class QqTag(MutableSequence):
    def __init__(self):
        self._children = []
    def __getitem__(self, idx: int) -> 'QqTag':
        return self._children[idx]

mypy complains that Signature of "__getitem__" incompatible with supertype "Sequence".

In Sequence, this method is defined as:

@abstractmethod
def __getitem__(self, index):
    raise IndexError

So, what's the problem and why mypy isn't happy with my implementation?


回答1:


As mentioned in comments, a typeof slice can also be passed. Ie, change idx: int to idx: Union[int, slice].

This will make mypy happy (at least on my machine ;):

class QqTag(MutableSequence):
    def __init__(self):
        self._children = []

    def __getitem__(self, idx: Union[int, slice]) -> 'QqTag':
        return self._children[idx]


来源:https://stackoverflow.com/questions/46685165/mypy-signature-of-getitem-incompatible-with-supertype-sequence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!