Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disallow literal 0 step in slice expressions #18065

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
13 changes: 13 additions & 0 deletions test-data/unit/check-expressions.test
Original file line number Diff line number Diff line change
Expand Up @@ -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
-- -------
Expand Down
4 changes: 2 additions & 2 deletions test-data/unit/check-tuples.test
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading