Skip to content
Open
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
50 changes: 50 additions & 0 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -2831,6 +2831,12 @@ def check_arg(
# Only non-abstract non-protocol class can be given where Type[...] is expected...
elif self.has_abstract_type_part(caller_type, callee_type):
self.msg.concrete_only_call(callee_type, context)
elif (
isinstance(context, SliceExpr)
and callable_name(callee) is not None
and self.check_slice_index_bounds(context, callee_type)
):
return
elif not is_subtype(caller_type, callee_type, options=self.chk.options):
error = self.msg.incompatible_argument(
n,
Expand All @@ -2853,6 +2859,50 @@ def check_arg(
caller_type, callee_type, context, error.code
)

def check_slice_index_bounds(self, slice: SliceExpr, expected_type: ProperType) -> bool:
"""Check that slice indexes have valid types for `__getitem__` or `__setitem__`

Validates start, stop, and step against the expected slice type from the method signature.
Reports an error for invalid index types.

Rejected examples,
x["foo":"bar"] # str indices when expecting int/SupportsIndex/None
x[:2:b] = y # if b doesn't match the expected step type
"""
expected_types = (
get_proper_types(expected_type.items)
if isinstance(expected_type, UnionType)
else [expected_type]
)
slice_types = [
typ
for typ in expected_types
if isinstance(typ, Instance)
and typ.type.fullname == "builtins.slice"
and len(typ.args) == 3
]
if len(slice_types) != 1:
return False

has_invalid_bounds = False
for index, expected_type in zip(
[slice.begin_index, slice.end_index, slice.stride], slice_types[0].args
):
if index is None:
continue
actual = (
self.chk.lookup_type(index) if self.chk.has_type(index) else self.accept(index)
)
if not is_subtype(actual, expected_type, options=self.chk.options):
self.chk.fail(
f"Slice index must be {format_type(expected_type, self.chk.options)}; "
f"got {format_type(actual, self.chk.options)}",
index,
code=codes.INDEX,
)
has_invalid_bounds = True
return has_invalid_bounds

def check_overload_call(
self,
callee: Overloaded,
Expand Down
34 changes: 34 additions & 0 deletions test-data/unit/check-expressions.test
Original file line number Diff line number Diff line change
Expand Up @@ -1232,6 +1232,40 @@ a[o:]
a[:o]
[builtins fixtures/slice.pyi]

[case testSliceBoundErrorReportsBoundType]
a: list[int]
s: str

a[1:] # Valid integer bounds should remain accepted.
a[:2]
a[::3]

# Invalid start, stop, and step bounds must each be reported at the bound.
a[s:] # E: Slice index must be "SupportsIndex | None"; got "str"
a[:s] # E: Slice index must be "SupportsIndex | None"; got "str"
a[::s] # E: Slice index must be "SupportsIndex | None"; got "str"
[builtins fixtures/slice.pyi]

[case testSliceBoundErrorReportsCustomType]
# Test that the error message respects actual types from the __getitem__ signature
from typing import Generic, TypeVar

T = TypeVar('T')

class CustomSliceable(Generic[T]):
def __getitem__(self, x: slice[str, str, str]) -> T: ...

c: CustomSliceable[int]
i: int

c["a":"b":"c"] # Valid string bounds should be accepted.

# Invalid bounds must report the expected type from the signature, not hardcoded types.
c[i:] # E: Slice index must be "str"; got "int"
c[:i] # E: Slice index must be "str"; got "int"
c[::i] # E: Slice index must be "str"; got "int"
[builtins fixtures/slice.pyi]

[case testSliceSupportsIndex]
import typing_extensions
class Index:
Expand Down
11 changes: 7 additions & 4 deletions test-data/unit/fixtures/slice.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
import types
from typing import Generic, TypeVar, Protocol
T = TypeVar('T')
_Tco = TypeVar('_Tco', covariant=True)
_StartTco = TypeVar('_StartTco', covariant=True)
_StopTco = TypeVar('_StopTco', covariant=True)
_StepTco = TypeVar('_StepTco', covariant=True)

class SupportsIndex(Protocol):
def __index__(self) -> int: ...
Expand All @@ -14,10 +16,11 @@ class type: pass
class tuple(Generic[T]): pass
class function: pass

class int: pass
class int:
def __index__(self) -> int: ...
class str: pass

class slice(Generic[_Tco]): pass
class slice(Generic[_StartTco, _StopTco, _StepTco]): pass
class dict: pass
class list(Generic[T]):
def __getitem__(self, x: slice[SupportsIndex | None]) -> list[T]: pass
def __getitem__(self, x: slice[SupportsIndex | None, SupportsIndex | None, SupportsIndex | None,]) -> list[T]: pass
Loading