Skip to content

Commit 6759dbd

Browse files
Infer generic type arguments for slice expressions (#18160)
Fixes #18149 Slices were made generic in python/typeshed#11637. Currently, all slice expressions are inferred to have type `slice[Any, Any, Any]`. This PR fills in the generic type arguments more appropriately using start/stop/stride expression types. Given ```python class Foo: def __getitem__[T](self, item: T) -> T: return item x = Foo() reveal_type(x[1:]) ``` Before: ```none main.py:5: note: Revealed type is "builtins.slice[Any, Any, Any]" ``` After: ```none main.py:5: note: Revealed type is "builtins.slice[builtins.int, None, None]" ```
1 parent 8ef2197 commit 6759dbd

File tree

2 files changed

+7
-3
lines changed

2 files changed

+7
-3
lines changed

mypy/checkexpr.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5612,11 +5612,15 @@ def visit_slice_expr(self, e: SliceExpr) -> Type:
56125612
except KeyError:
56135613
supports_index = self.chk.named_type("builtins.int") # thanks, fixture life
56145614
expected = make_optional_type(supports_index)
5615+
type_args = []
56155616
for index in [e.begin_index, e.end_index, e.stride]:
56165617
if index:
56175618
t = self.accept(index)
56185619
self.chk.check_subtype(t, expected, index, message_registry.INVALID_SLICE_INDEX)
5619-
return self.named_type("builtins.slice")
5620+
type_args.append(t)
5621+
else:
5622+
type_args.append(NoneType())
5623+
return self.chk.named_generic_type("builtins.slice", type_args)
56205624

56215625
def visit_list_comprehension(self, e: ListComprehension) -> Type:
56225626
return self.check_generator_or_comprehension(

test-data/unit/check-expressions.test

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1178,8 +1178,8 @@ class B: pass
11781178
[case testSlicingWithInvalidBase]
11791179

11801180
a: A
1181-
a[1:2] # E: Invalid index type "slice" for "A"; expected type "int"
1182-
a[:] # E: Invalid index type "slice" for "A"; expected type "int"
1181+
a[1:2] # E: Invalid index type "slice[int, int, None]" for "A"; expected type "int"
1182+
a[:] # E: Invalid index type "slice[None, None, None]" for "A"; expected type "int"
11831183
class A:
11841184
def __getitem__(self, n: int) -> 'A': pass
11851185
[builtins fixtures/slice.pyi]

0 commit comments

Comments
 (0)