python / python/mypy

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

Open
#20,058 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-literal-types topic-protocols
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.