diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 577576a4e5f8b..1bb6ffbb908e2 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -5616,6 +5616,13 @@ def visit_slice_expr(self, e: SliceExpr) -> Type: if index: t = self.accept(index) self.chk.check_subtype(t, expected, index, message_registry.INVALID_SLICE_INDEX) + + if e.stride: + stride_literals = self.try_getting_int_literals(e.stride) + if stride_literals is not None and 0 in stride_literals: + self.msg.fail("Slice step cannot be 0", index) + return AnyType(TypeOfAny.from_error) + return self.named_type("builtins.slice") def visit_list_comprehension(self, e: ListComprehension) -> Type: diff --git a/test-data/unit/check-expressions.test b/test-data/unit/check-expressions.test index d5ddc910bcd63..af1befaa9d5a5 100644 --- a/test-data/unit/check-expressions.test +++ b/test-data/unit/check-expressions.test @@ -1235,6 +1235,19 @@ a[None:] a[:None] [builtins fixtures/slice.pyi] +[case testSliceStepZero] +from typing import Any +from typing_extensions import Literal +n1: Literal[0] +n2: Literal[0, 1] +a: Any +a[::0] # E: Slice step cannot be 0 +a[::-0] # E: Slice step cannot be 0 +a[::+0] # E: Slice step cannot be 0 +a[::n1] # E: Slice step cannot be 0 +a[::n2] # E: Slice step cannot be 0 +[builtins fixtures/tuple.pyi] + -- Lambdas -- ------- diff --git a/test-data/unit/check-tuples.test b/test-data/unit/check-tuples.test index d675a35c4aae6..a7562d1b7322f 100644 --- a/test-data/unit/check-tuples.test +++ b/test-data/unit/check-tuples.test @@ -1440,8 +1440,8 @@ t[y:] # E: Slice index must be an integer, SupportsIndex or None [case testTupleSliceStepZeroNoCrash] # This was crashing: https://github.com/python/mypy/issues/18062 -# TODO: emit better error when 0 is used for step -()[::0] # E: Ambiguous slice of a variadic tuple +()[::0] # E: Ambiguous slice of a variadic tuple \ + # E: Slice step cannot be 0 [builtins fixtures/tuple.pyi] [case testInferTupleTypeFallbackAgainstInstance]