python / python/mypy

Cannot infer generic parameter types within `match` statements

Aperta
#18,432 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug Report

Related to #13612.

#13618 fixed the error reported in #13612, so mypy correctly infers the type of the unpacked value.

However, mypy does not correctly infer the type parameter of the class containing the generic attribute within the scope of the match statement, despite correct inference outside the statement.

To Reproduce

Extending the reprex from #13612:

from typing import Generic, TypeVar

T = TypeVar("T")


class A(Generic[T]):
    x: T

    __match_args__ = ("x",)

    def __init__(self, x: T):
        self.x = x


a = A("foo")
reveal_type(a)    # A[builtins.str] (correct)
reveal_type(a.x)  # builtins.str (correct)

match a:
    case A(x) as a_match:
        reveal_type(x)          # builtins.str (correct)
        reveal_type(a_match)    # A[Any]  **(incorrect! should be A[str])**

Expected Behavior

Within the match statement, A(x) should be inferred to be of type A[str].

Revealed type is "test_generic.A[builtins.str]"
Revealed type is "builtins.str"
Revealed type is "builtins.str"
Revealed type is "test_generic.A[builtins.str]"

I have found that pyright, or at least the pylance VS code extension, infers this correctly. See below:

Screenshot 2025-01-09 at 4 25 24 PM

Actual Behavior

The final line does not reveal A[str].

Revealed type is "test_generic.A[builtins.str]"
Revealed type is "builtins.str"
Revealed type is "builtins.str"
Revealed type is "test_generic.A[Any]"

Your Environment

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

Motivation

This becomes relevant when trying to match on a union of generic types, as it creates an unreachable error.

e.g.

type Union_AB[T] = A[T] | B[T]

def func(val: Union_AB[int]) -> None:
    match val:
        case A(x):
            pass
        case B(x):  #  error: Subclass of "A[int]" and "B[Any]" cannot exist: would have incompatible method signatures  [unreachable]
            pass

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 il riproduttore generico match fornito con mypy 1.14.1 e confronta i tipi rivelati con l’output previsto. Traccia l’inferenza del pattern matching di mypy per il valore a_match catturato, quindi aggiungi la copertura di regressione per i pattern di classi generiche e conferma che l’esempio di unione non segnali più l’errore errato di codice irraggiungibile.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.