mypy:“__getitem__”的签名与超类型“序列”不兼容

时间:2017-10-11 09:54:41

标签: python typechecking mypy

我有一个继承自MutableSequence的类:

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

mypy 抱怨Signature of "__getitem__" incompatible with supertype "Sequence"

Sequence中,此方法定义为:

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

那么,问题是什么以及为什么 mypy 对我的实施不满意呢?

1 个答案:

答案 0 :(得分:2)

如评论中所述,也可以传递typeof切片。即,将idx: int更改为idx: Union[int, slice]

这会让mypy高兴(至少在我的机器上;):

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

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