python / python/mypy

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

Offen
#20,970 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

feature
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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.

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

In der Issue werden keine Implementierungsdatei, kein Test und kein Einstiegspunkt genannt. Beginne damit, test1 und test2 in mypy zu reproduzieren, und untersuche dann die Inferenzpfade für getaggte TypedDicts und Literale; als abgeschlossen gilt die Aufgabe, wenn die gezeigten Zuweisungen ohne explizite Verzweigung akzeptiert werden.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
45/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.