`Literal["..."]`s incorrectly assignable to protocol with `__getitem__(slice) -> Self`
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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"])
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Run the linked mypy-play reproduction with mypy 1.18.2, then trace how protocol bounds, Self-returning getitem, and Literal string slicing are checked. Done means the example rejects Literal["banana"] as satisfying Slicable and no longer reveals the sliced results as that literal type.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100