mirror of
https://github.com/astral-sh/ruff.git
synced 2026-11-21 20:29:20 +08:00
## Summary
Prior to this change, when a slice bound was not an integer literal,
boolean literal, or `None`, we inferred a bare `slice[Any, Any, Any]`.
This erased enough information that subscription checking accepted
invalid slices even when `__getitem__` requires `SupportsIndex | None`
bounds:
```python
def get(values: list[int], start: float) -> list[int]:
return values[start:] # error: [invalid-argument-type]
```
(This may have been waiting on
https://github.com/astral-sh/ruff/commit/cb58704e085fe7e70d72842294575de47e47bead?)
We now preserve the inferred type of each provided slice bound in
`slice[...]`, so ordinary argument checking diagnoses invalid bounds for
built-in sequences and user-defined `__getitem__` methods with typed
slice parameters.
Closes https://github.com/astral-sh/ty/issues/3547.
1.6 KiB
1.6 KiB
Bytes subscripts
Indexing
b = b"\x00abc\xff"
reveal_type(b[0]) # revealed: Literal[0]
reveal_type(b[1]) # revealed: Literal[97]
reveal_type(b[4]) # revealed: Literal[255]
reveal_type(b[-1]) # revealed: Literal[255]
reveal_type(b[-2]) # revealed: Literal[99]
reveal_type(b[-5]) # revealed: Literal[0]
reveal_type(b[False]) # revealed: Literal[0]
reveal_type(b[True]) # revealed: Literal[97]
x = b[5] # error: [index-out-of-bounds] "Index 5 is out of bounds for bytes literal `Literal[b"\x00abc\xff"]` with length 5"
reveal_type(x) # revealed: Unknown
y = b[-6] # error: [index-out-of-bounds] "Index -6 is out of bounds for bytes literal `Literal[b"\x00abc\xff"]` with length 5"
reveal_type(y) # revealed: Unknown
def _(n: int):
a = b"abcde"[n]
reveal_type(a) # revealed: int
Slices
b: bytes = b"\x00abc\xff"
reveal_type(b[0:2]) # revealed: Literal[b"\x00a"]
reveal_type(b[-3:]) # revealed: Literal[b"bc\xff"]
b[0:4:0] # error: [zero-stepsize-in-slice]
b[:4:0] # error: [zero-stepsize-in-slice]
b[0::0] # error: [zero-stepsize-in-slice]
b[::0] # error: [zero-stepsize-in-slice]
def _(m: int, n: int):
byte_slice1 = b[m:n]
reveal_type(byte_slice1) # revealed: bytes
def _(s: bytes) -> bytes:
byte_slice2 = s[0:5]
return reveal_type(byte_slice2) # revealed: bytes
def invalid_slice_bound(value: bytes, start: float) -> bytes:
return value[start:] # error: [invalid-argument-type]
Bytearray slices
def invalid_slice_bound(value: bytearray, start: float) -> bytearray:
return value[start:] # error: [invalid-argument-type]