2

I am working with time series, and want to retrieve and slice by date/time. Ideally, I'd leverage the existing [:] syntax.

For example (see last line):

from datetime import datetime
from typing import Union


class T:
    def __getitem__(self, key: datetime | slice) -> Union['T', float]:
        if isinstance(key, slice):
            return T()
        if isinstance(key, datetime):
            return 42
        raise ValueError()


t = T()
v = t[datetime(2020, 1, 1)]                        # OK
t2 = t[datetime(2020, 1, 1):datetime(2021, 1, 1)]  # Not OK

This runs fine, but when running it through mypy, it produces this error on the last line:

error: Slice index must be an integer, SupportsIndex or None  [misc]
Found 1 error in 1 file (checked 1 source file)

Short of disabling this error altogether, is there a method to make this code pass mypy?

Or am I doing something I should not be doing?

Oblomov
  • 55
  • 4
  • 1
    No, you aren't doing anything wrong. This is an unreasonable restriction on the `slice` type. See [this](https://github.com/python/mypy/issues/2410) longstanding issue. – Daniil Fajnberg Apr 19 '23 at 19:17
  • That's indeed exactly the issue. As per ticket in github, I have added # type: ignore[misc] comments at the offending lines. – Oblomov May 17 '23 at 11:23
  • 1
    I recently opened a [PR](https://github.com/python/typeshed/pull/10174) to make `slice` generic, but it was put on hold at least until [PEP 696](https://peps.python.org/pep-0696/) lands. So it might take a while for this to be resolved. But I'll do my best to stay on top of it and re-submit the PR, as soon as we have the missing tools. – Daniil Fajnberg May 17 '23 at 11:47

0 Answers0