python / python/mypy

TypeVar leaks out of `__init__` with self-type

Open
#18,185 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

A typevar (not concrete) leaks out of a __init__ call in some overloaded contexts.

To Reproduce

from __future__ import annotations

from typing import Generic, TypeVar, overload, Callable

T = TypeVar("T")
U1 = TypeVar("U1")
U2 = TypeVar("U2")

class X(Generic[T]):
    @overload
    def __init__(self: X[U1], *, x: U1) -> None: ...
    @overload
    def __init__(self: X[U2], *, y: U2) -> None: ...
    
    def __init__(self: X[U1 | U2], *, x: U1 | None = None, y: U2 | None = None, z: Callable[[U1], None] | Callable[[U2], None] | None = None):
        self.z = z

reveal_type(X(x=5).z)  # N: Revealed type is "Union[def (U1`-1), def (U2`-2), None]"

here's a minimum reproduction, the above is only relevant as "why would you want this?":

from __future__ import annotations

from typing import Generic, TypeVar, Callable

T = TypeVar("T")
U = TypeVar("U")

class X(Generic[T]):
    def __init__(self: X[U], x: U):
        self.x = x

reveal_type(X(x=5).x)

Expected Behavior

# N: Revealed type is Union[def (int), def (int), None] or # N: Revealed type is Union[def (int), None].

Actual Behavior

# N: Revealed type is "Union[def (U1`-1), def (U2`-2), None]"

Your Environment

Tested in mypy-play.

  • Mypy version used: 1.13
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.12

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

Start by running the minimum reproduction in mypy-play with mypy 1.13 and compare the revealed type with the expected concrete int result. Trace how generic self-types are inferred during the init call, then add a regression test showing that the TypeVar does not escape into the revealed type.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
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.