Skip to content

TypeVar leaks out of __init__ with self-type #18185

Open
@A5rocks

Description

@A5rocks

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions