ruff/crates/red_knot_python_semantic/resources/mdtest/subscript/bytes.md
Shunsuke Shibayama 78b5f0b165
[red-knot] detect invalid return type (#16540)
## Summary

This PR closes #16248.

If the return type of the function isn't assignable to the one
specified, an `invalid-return-type` error occurs.
I thought it would be better to report this as a different kind of error
than the `invalid-assignment` error, so I defined this as a new error.

## Test Plan

All type inconsistencies in the test cases have been replaced with
appropriate ones.

---------

Co-authored-by: Carl Meyer <carl@astral.sh>
2025-03-12 01:58:59 +00:00

1.6 KiB

Bytes subscripts

Indexing

b = b"\x00abc\xff"

reveal_type(b[0])  # revealed: Literal[b"\x00"]
reveal_type(b[1])  # revealed: Literal[b"a"]
reveal_type(b[4])  # revealed: Literal[b"\xff"]

reveal_type(b[-1])  # revealed: Literal[b"\xff"]
reveal_type(b[-2])  # revealed: Literal[b"c"]
reveal_type(b[-5])  # revealed: Literal[b"\x00"]

reveal_type(b[False])  # revealed: Literal[b"\x00"]
reveal_type(b[True])  # revealed: Literal[b"a"]

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]
    # TODO: Support overloads... Should be `bytes`
    reveal_type(a)  # revealed: @Todo(return type of decorated function)

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]
    # TODO: Support overloads... Should be `bytes`
    reveal_type(byte_slice1)  # revealed: @Todo(return type of decorated function)

def _(s: bytes) -> bytes:
    byte_slice2 = s[0:5]
    # TODO: Support overloads... Should be `bytes`
    return reveal_type(byte_slice2)  # revealed: @Todo(return type of decorated function)