Reputation: 8077
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?
Upvotes: 11
Views: 2882
Reputation: 85
Another option is to use the typing.overload decorator.
from typing import overload
class QqTag(MutableSequence):
def __init__(self):
self._children = []
@overload
def __getitem__(self, i: int) -> 'QqTag':
...
@overload
def __getitem__(self, s: slice) -> list['QqTag']:
...
def __getitem__(self, idx):
return self._children[idx]
See examples from typing or PEP 484 -- Type Hints.
Upvotes: 2
Reputation: 2768
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]
Upvotes: 7