I’d like to be able to define a TimeSeries class as
T = TypeVar("T")
class TimeSeries(dict[datetime, T]):
def __getitem__( # type: ignore[override]
self,
key: "datetime | slice[datetime, datetime]",
) -> "T | TimeSeries[T]":
if not isinstance(key, slice):
return super().__getitem__(key)
return TimeSeries((t, v) for (t, v) in self.items() if key.start <= t < key.stop)
so that I can slice my data with syntax data[start:stop] that works the same way as slicing lists.
as far as the Python is concerned, there is no problem.
But I can’t find a way to type-hint this. I found a discussion going back to 2015 where people requested that slice should be generic[1]. To be clear, the problem is that mypy raises error: Slice index must be an integer, SupportsIndex or None [misc] for all the lines where I actually use the datetime slices. I don’t think this is workable syntax if I have to put # type: ignore[misc] on all the lines where I slice the data series. Then it will be more readable to instead use a .slice(start, stop) method, and from there I wouldn’t be surprised if I slide towards using straight dict[datetime, T] with a series of functions instead of methods.
Which isn’t the end of the world. But I would like it if there was a better solution ^^