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

问题描述 投票:4回答:1

我有一个继承自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对我的实现不满意?

python typechecking mypy
1个回答
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]
© www.soinside.com 2019 - 2024. All rights reserved.