Skip to content

Use literal overloads when inferring generic protocol arguments - #22436

Closed
sakshichitnis27 wants to merge 1 commit into
python:masterfrom
sakshichitnis27:issue-22199-general
Closed

sakshichitnis27 wants to merge 1 commit into
python:masterfrom
sakshichitnis27:issue-22199-general

Conversation

@sakshichitnis27

Copy link
Copy Markdown

Fixes #22199

Currently mypy infers object for R below, because a TypedDict is matched
against the protocol through its Mapping[str, object] fallback:

class X(TypedDict):
    a: int
    b: str

class GetX[K, V](Protocol):
    def __getitem__(self, key: K, /) -> V: ...

def f[T, R](k: T, d: GetX[T, R]) -> R: ...

reveal_type(f("b", x))  # now "str", was "object"

The same limitation affects any class whose protocol member is overloaded on
Literal parameters: the first overload item is picked while inferring, so
f("b", y) failed with "Cannot infer value of type parameter T".

This PR reuses the existing two-pass inference for these cases:

  • If a generic protocol argument is implemented by an actual type using
    Literal-parameter overloads (or is a TypedDict and the protocol has
    __getitem__), and a type variable of the protocol is also used by another
    parameter, inference first runs without that argument. If the first pass
    gives a literal value for a type variable (e.g. "b"), and the argument is
    compatible with the protocol after substituting it, the argument is used in
    the second pass with the literal preserved (Literal["b"] instead of str),
    so the matching overload item can be selected.
  • Otherwise inference works exactly as before. For example, if the protocol
    also has keys() -> Iterable[K], a literal key can't work, and the old
    result is kept.
  • For protocol checks and inference, __getitem__ of a TypedDict is treated as
    one overload per key followed by the usual (str) -> object method. Because
    of the last item, everything that was accepted before is still accepted.

Things reviewers may want to look at:

  • The type variable for the key keeps the literal, so e.g.
    def g[K, V](k: K, d: GetX[K, V]) -> tuple[K, V] gives
    tuple[Literal["b"], str] for g("b", x).
  • Overloads that are not selected by literal values are not affected (there is
    a test for that), and I did not try to improve union-of-literals keys.

Testing

  • New tests in check-typeddict.test and check-protocols.test; they fail
    without the change (except the "unchanged" ones, which pass both ways).
  • python -m pytest -n 4 mypy/test (12361 passed)
  • python -m mypy --config-file mypy_self_check.ini -p mypy -p mypyc
  • Pre-commit style checks (black, ruff, codespell) on the changed files.
  • I also compared mypy output before and after the change on a few installed
    packages (attrs, _pytest, pip, virtualenv, ...) and on randomly generated
    programs; the only differences were the intended improvements.

I used an LLM assistant while investigating this and drafting the change, and I
have reviewed and tested the code myself.

🤖 Generated with Claude Code

If a generic protocol argument is implemented with overloads that are
selected by literal values (or is a TypedDict and the protocol has
__getitem__), infer it in the second pass and keep the literal value of
type variables from the first pass. Treat TypedDict __getitem__ as having
an overload for each key. If the literal can't be used, inference works
as before.

Fixes python#22199

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Allow tighter types with protocols and overloads

2 participants