I want to use slice[int]
like list[int]
, but my IDE tells me that this usage is invalid. So how to annotate slice type, if I want to constrain the type of its parameters?

- 99
- 5
-
Could you provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) of your problem? – M Z Apr 28 '23 at 01:22
-
You can use something like this - `def func(var1: List[int], var2: slice)`: `return var1[s]` – Pravash Panigrahi Apr 28 '23 at 05:12
-
This should help: https://stackoverflow.com/questions/68876078/python-type-annotation-for-slice. I guess you could also use Tuple[int]? – nb123 Apr 28 '23 at 06:38
1 Answers
Update (2023-05-12)
I opened a PR to make slice
generic. The change would introduce quite a few mypy
errors in many existing projects. The good people at python/typeshed
made it clear that until we have type variable defaults (proposed in PEP 696, but not yet accepted) and the slice
type utilizes them, they will not accept the change to make it generic.
I will try to keep up to date on the progress with PEP 696 and to implement the missing changes as soon as possible.
Original answer
As it stands right now, the built-in slice
type is not generic, so it has no type parameters (unlike e.g. list
). There has been a long-standing discussion about this (since 2015) and the relevant typeshed
issue is still open. IMO it should definitely be made generic, but it is unclear if/when that will happen.
slice
arguments can be of any type (source). This means a statement like e.g. slice("foo", [-1], object())
will pass mypy --strict
(even though it may be of questionable utility).
That means there is currently no way to constrain a slice type variable in terms of its start/stop/step attribute types.
And since you cannot even subclass slice
, there is not even a way to easily make your own generic slice-like type.

- 12,753
- 2
- 10
- 41
-
There is such a way: `it TYPE_CHECKING: class MySlice(Generic[_T]): ...; else: MySlice = slice` (the last line may need a `type: ignore` comment). This way you can make your own slice typing easily. – STerliakov Apr 30 '23 at 13:07
-
1@SUTerliakov True, but that does not really help in any practical context. Whenever you actually need to _use_ a slice object, e.g. for slicing a `list`, the type checker will not accept `MySlice` unless it inherits from `builtins.slice`. You would need to convert/cast your custom `MySlice` into a normal `slice` or place `# type: ignore` directives everywhere. – Daniil Fajnberg May 01 '23 at 13:14
-
Ah, you're right. However, something like [this](https://mypy-play.net/?mypy=master&python=3.10&flags=strict&gist=77b5d146011b991b9a04b065d337b2c6) (inheriting from slice in `if TYPE_CHECKING` with ignore comment for final class - anyway this code is never executed) works. – STerliakov May 01 '23 at 14:05