python / python/mypy

PEP-646 generic with self annotated function gives incorrect result

Open
#21,878 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-self-types
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

When a class is generic over a PEP-646/TypeVarTuple/varadic generic and uses that outer generic in a self annotated function, the result of calling that function is incorrect.

To Reproduce

https://mypy-play.net/?gist=e1eb19d739dd5cdc55e99e1ead4fc55c

from typing import reveal_type

class A[*TS]:
    def __init__(self, *state: *TS):
        self.state: tuple[*TS] = state

    def add(self: A[*TS, int, int]) -> A[*TS, int]:
        return A(*self.state[:-2], self.state[-2] + self.state[-1])

# Expected type: "A[1, int]" or "A[1, 5]" or similar
# Actual: Revealed type is "__main__.A[Literal[1]?, Literal[2]?, Literal[3]?, int]"
reveal_type(A(1, 2, 3).add())

Expected Behavior

Mypy should either give the correct type for A(1, 2, 3).add(), or give an error somewhere.

Actual Behavior

Mypy silently gives the wrong type for A(1, 2, 3).add()

Your Environment

  • Mypy version used: Playground 2.3.1

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

Reproduce the linked mypy-play example, starting with reveal_type(A(1, 2, 3).add()) and the PEP-646 self annotation shown in the issue. Trace generic inference for the add method; done means mypy reports the correct result or an error instead of silently revealing the wrong type, validated against the reproduction.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.