How does a minimal implementation of a Sequence from collections.abc, together with the correct type hints, look like?
According to its documentation, __len__ and __getitem__ are sufficient. My type hinter complains about the implementation of __getitem__ though, although my implementation follows the python docs.
My current version is the following (with warnings from basedpyright):
from collections.abc import Sequence
from typing import override
class MySeq(Sequence[float]):
def __init__(self):
self._data: list[float] = list()
@override
def __len__(self) -> int:
return len(self._data)
@override
def __getitem__(self, key) -> float: # Type annotation is missing for parameter "key"
return self._data[key] # Return type is unknown
- How do I type hint
key? Justkey: intis not accepted by the type checker. It gives the warning:"slice[Any, Any, Any]" is not assignable to "int". What choices do I have here? - What is wrong with the return type? The full warning is
"float" is not assignable to "Sequence[float]"
key: intis not accepted by the type checker" - so what does it tell you? Mypy shows the missing overload;Sequences can also be sliced: docs.python.org/3/reference/datamodel.html#object.__getitem__overload, notoverride- you can index into aSequencewith anintor aslice, therefore receiving either afloator aSequence[float], as the errors tell you.slicearguments fromSequence.__get_item__, even though nothing in the documentation indicates that you need to accept anything other than an integer key. (I suspect that is a shortcoming in the documentation, though, rather than an overreach by the signature defined intypeshed/stdlib/typing.pyi