python / python/mypy

Feature request: infer pre-narrowed tagged union as a Union of possible types

Aperta
#20,970 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

I'm building a tagged union inside of a function, like so:

from typing import Literal, TypedDict

class Foo(TypedDict):
    tag: Literal["foo"]

class Bar(TypedDict):
    tag: Literal["bar"]
    
def test1(tag: Literal["foo", "bar"]) -> Foo | Bar:
    return {"tag": tag}  # error

Because tag hasn't been narrowed to "foo" or "bar" at the return site, it's considered not to be assignable to FooOrBar, even though there are no other possible outcomes. To fix this, I have to return the same value from both branches of an if clause:

def test2(tag: Literal["foo", "bar"]) -> Foo | Bar:
    if tag == "foo":
        return {"tag": tag}  # ok
    else:
        return {"tag": tag}  # ok

At this stage all I care about is knowing that my output value is one of Foo or Bar, and the above construct looks like a code smell (especially with >2 tag values).

MyPy also sees this as an error even when defining the literal value inline if my variable is annotated with multiple possible values:

tag: Literal["foo", "bar"] = "foo"
foo: Foo | Bar = {"tag": tag}  # error

Pitch
In cases where the "tag" value of the tagged union is not narrowed, but can be inferred as consistent with multiple typed dicts in the return type of a function, I'd love to see this be narrowed as a union of those possible typed dicts. Given the "tag" is already scoped to the possible values (if it weren't, the bare "else" wouldn't work) I can't think of any way this would be unsound.

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

Nell’issue non vengono indicati file di implementazione, test o punto di ingresso. Inizia riproducendo test1 e test2 in mypy, quindi analizza i percorsi di inferenza per TypedDict con tag e Literal; il lavoro è completato quando le assegnazioni mostrate vengono accettate senza richiedere un branching esplicito.

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

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
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.