Skip to content

Literal["..."]s incorrectly assignable to protocol with __getitem__(slice) -> Self #20058

@decorator-factory

Description

@decorator-factory

Bug Report

Values of Literal["..."] types are incorrectly assignable to a protocol where __getitem__(slice) returns Self

To Reproduce

from typing import Protocol, Self, Literal class Slicable(Protocol): def __getitem__(self, arg: slice, /) -> Self: ... class Parser[X: Slicable]: def handle(self, input: X) -> tuple[X, X]: return input[:2], input[2:] parser = Parser[Literal["banana"]]() #^ no error, but expected: Literal['banana'] does not satisfy Slicable bound left, right = parser.handle("banana") reveal_type(left) # revealed as: Literal['banana'], but 'ba' at runtime reveal_type(right) # revealed as: Literal['banana'], but 'nana' at runtime

https://mypy-play.net/?mypy=1.18.2&python=3.14&flags=strict&gist=315731e775d05e4b59aa0105b8f96893

Literal["banana"] should not be assignable to Slicable, because slicing a Literal["banana"] produces LiteralString, not necessarily the type itself (which would only have to be Literal["banana"])

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions