I'm trying to implement a kind of custom sequence class in Python:
from typing import Sequence, TypeVar, List
T = TypeVar('T')
class MySequence(Sequence[T]):
def __init__(self):
self._container: Sequence[T] = []
def __getitem__(self, idx):
return self._container[idx]
def __len__(self):
return len(self._container)
Now I want to check that mypy is aware that elements of MySequence are items of type T:
foo: MySequence[str] = MySequence()
reveal_type(foo[0])
# Revealed type is 'Any'
So it fails: mypy knows nothing about items of foo. The same example for ordinary Sequence works:
bar: Sequence[str] = []
reveal_type(bar[0])
# Revealed type is 'builtins.str*'
If I'm trying to add type annotations to __getitem__ implementation, I have another error:
def __getitem__(self, idx) -> T:
# Signature of "__getitem__" incompatible with supertype "Sequence"
I also tried
def __getitem__(self, idx) -> Union[T, Sequence[T]]:
as idx can be a slice and in that case my code will return a sequence instead of one element. It fails either with the same message.
As discussed in my previous question, there is an open discussion on issues like that.
However, I still wonder, is it possible to create custom sequence types that allow mypy to extract information about the type of its items, like in my example?