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
10 changes: 9 additions & 1 deletion mypy/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2941,7 +2941,15 @@ def slice(
total = len(self.items)
unpack_index = find_unpack_in_list(self.items)
assert unpack_index is not None
if begin is None and end is None:
if (
begin is not None
and end is not None
and (begin >= 0) == (end >= 0)
and (begin >= end if stride is None or stride > 0 else begin <= end)
):
# Start and end count from the same side, so the slice is empty for any length.
slice_items = []
elif begin is None and end is None:
# We special-case this to support reversing variadic tuples.
# General support for slicing is tricky, so we handle only simple cases.
if stride == -1:
Expand Down
15 changes: 15 additions & 0 deletions test-data/unit/check-typevar-tuple.test
Original file line number Diff line number Diff line change
Expand Up @@ -1587,6 +1587,21 @@ bt = t[::0] # E: Slice step cannot be zero
reveal_type(bt) # N: Revealed type is "builtins.tuple[Any, ...]"
[builtins fixtures/tuple.pyi]

[case testVariadicTupleEmptySlice]
from typing import Unpack, TypeVarTuple

Ts = TypeVarTuple("Ts")
def f(x: tuple[int, Unpack[Ts], str], y: tuple[int, Unpack[tuple[str, ...]]]) -> None:
reveal_type(x[2:1]) # N: Revealed type is "tuple[()]"
reveal_type(x[3:3]) # N: Revealed type is "tuple[()]"
reveal_type(x[-1:-2]) # N: Revealed type is "tuple[()]"
reveal_type(x[1:2:-1]) # N: Revealed type is "tuple[()]"
reveal_type(y[5:2]) # N: Revealed type is "tuple[()]"
reveal_type(y[-3:-3:2]) # N: Revealed type is "tuple[()]"
y[1:5] # E: Ambiguous slice of a variadic tuple
y[-2:-5:-1] # E: Ambiguous slice of a variadic tuple
[builtins fixtures/tuple.pyi]

[case testAnyVariadicTupleLenientUnpacking]
from typing import Any, Unpack

Expand Down
Loading