Skip to content

Commit 5d91cdc

Browse files
committed
Disallow literal 0 step in slice expression
1 parent 06a566b commit 5d91cdc

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

mypy/checkexpr.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5616,6 +5616,13 @@ def visit_slice_expr(self, e: SliceExpr) -> Type:
56165616
if index:
56175617
t = self.accept(index)
56185618
self.chk.check_subtype(t, expected, index, message_registry.INVALID_SLICE_INDEX)
5619+
5620+
if e.stride:
5621+
stride_literals = self.try_getting_int_literals(e.stride)
5622+
if stride_literals is not None and 0 in stride_literals:
5623+
self.msg.fail("Slice step cannot be 0", index)
5624+
return AnyType(TypeOfAny.from_error)
5625+
56195626
return self.named_type("builtins.slice")
56205627

56215628
def visit_list_comprehension(self, e: ListComprehension) -> Type:

test-data/unit/check-expressions.test

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1235,6 +1235,19 @@ a[None:]
12351235
a[:None]
12361236
[builtins fixtures/slice.pyi]
12371237

1238+
[case testSliceStepZero]
1239+
from typing import Any
1240+
from typing_extensions import Literal
1241+
n1: Literal[0]
1242+
n2: Literal[0, 1]
1243+
a: Any
1244+
a[::0] # E: Slice step cannot be 0
1245+
a[::-0] # E: Slice step cannot be 0
1246+
a[::+0] # E: Slice step cannot be 0
1247+
a[::n1] # E: Slice step cannot be 0
1248+
a[::n2] # E: Slice step cannot be 0
1249+
[builtins fixtures/tuple.pyi]
1250+
12381251

12391252
-- Lambdas
12401253
-- -------

0 commit comments

Comments
 (0)