python / python/mypy

Type narrowing on object attribute with match statement doesn't apply

Aperta
#14,911 4 commenti 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

feature topic-match-statement topic-type-narrowing
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

The bug
It seems that doing a "type checking" with the object UI in pattern matching seems to not work properly.
Attribute match is not considered.

Code

class Test:
    def __init__(self, a: int | str):
        self.a: int | str = a

test = Test(5)

match test:
    case Test(a = int()):
        print(test.a + 3)
    case Test(a = str()):
        print(test.a + "3")

Expected behavior
By doing a match with Test(a = int()), python will check test is of type Test AND test.a is of type int.
But mypy "only assert" that test if of type Test. It keep the type int | str for test.a.

Reproduce :
On mypy-playground :
https://mypy-play.net/?mypy=latest&python=3.11&gist=6f05124abd1ef68032d59651a7d5c6c3

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 con il riproduttore mypy-playground collegato nell’issue e segui come l’istruzione match gestisce i pattern Test(a=int()) e Test(a=str()). Confronta il tipo inferito di test.a in ciascun ramo. Il lavoro è completato quando l’attributo viene ristretto rispettivamente a int o str, con il comportamento coperto da un test di regressione.

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

Valutazione

Stack tecnologico
python
Ambito
devtools
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.