Skip to content

Infer generic type arguments for slice expressions #18160

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

Merged
merged 2 commits into from
Nov 19, 2024
Merged
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
6 changes: 5 additions & 1 deletion mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -5612,11 +5612,15 @@ def visit_slice_expr(self, e: SliceExpr) -> Type:
except KeyError:
supports_index = self.chk.named_type("builtins.int") # thanks, fixture life
expected = make_optional_type(supports_index)
type_args = []
for index in [e.begin_index, e.end_index, e.stride]:
if index:
t = self.accept(index)
self.chk.check_subtype(t, expected, index, message_registry.INVALID_SLICE_INDEX)
return self.named_type("builtins.slice")
type_args.append(t)
else:
type_args.append(NoneType())
return self.chk.named_generic_type("builtins.slice", type_args)

def visit_list_comprehension(self, e: ListComprehension) -> Type:
return self.check_generator_or_comprehension(
Expand Down
4 changes: 2 additions & 2 deletions test-data/unit/check-expressions.test
Original file line number Diff line number Diff line change
Expand Up @@ -1178,8 +1178,8 @@ class B: pass
[case testSlicingWithInvalidBase]

a: A
a[1:2] # E: Invalid index type "slice" for "A"; expected type "int"
a[:] # E: Invalid index type "slice" for "A"; expected type "int"
a[1:2] # E: Invalid index type "slice[int, int, None]" for "A"; expected type "int"
a[:] # E: Invalid index type "slice[None, None, None]" for "A"; expected type "int"
class A:
def __getitem__(self, n: int) -> 'A': pass
[builtins fixtures/slice.pyi]
Expand Down
Loading