python / python/mypy

TypeVar leaks out of `__init__` with self-type

Aperta
#18,185 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-self-types topic-type-variables
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia eseguendo la riproduzione minima in mypy-play con mypy 1.13 e confronta il tipo rivelato con il risultato concreto int previsto. Traccia quindi come vengono dedotti i self-type generici durante la chiamata a init, poi aggiungi un test di regressione che mostri che il TypeVar non confluisce nel tipo rivelato.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.