python / python/mypy

(🐞) `overload`s that exhaust finite `Literal`s(`bool`/`Enum`) not treated as exhaustive

Offen
#14,764 14 Kommentare 30 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-literal-types topic-overloads
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

@overload
def foo(a: Literal[True]) -> int: ...

@overload
def foo(a: Literal[False]) -> str: ...

def foo(a: bool) -> object: ...

a: bool
reveal_type(foo(a))  # error: No overload variant of "foo" matches argument type "bool"
@overload
def foo(a: Literal[True]) -> int: ...

@overload
def foo(a: Literal[False]) -> str: ...

@overload
def foo(a: bool) -> object: ...  # no error regarding impossible to match overload

a: bool
reveal_type(foo(a))  # object
@overload
def foo(a: Literal[True, False]) -> int | str: ...

@overload
def foo(a: bool) -> object: ...  # error: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader

def foo(a: bool) -> object: ...

a: bool
reveal_type(foo(a))  # int | str

Here mypy incorrectly forces us to implement a completely redundant overload for the non Literal case when it is already exhaustively covered by both literals. It is only when the literals are in the same overload (useless in practice, but just for demonstration) that mypy correctly handles this case.

Mypy should be doing 'union math' (or what ever it's called) to apply both literal overloads at once.

This also affects all other exhaustible Literals such as Enums.

This example is pulled directly from the docs, so I think they should be updated as well to an example that doesn't contain this confusing defect.

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

Beginne damit, die Overload-Beispiele im Issue zu reproduzieren, und lies die verlinkte Dokumentation zu Literal types. Verfolge mypy's Overload-Matching und die Verarbeitung endlicher Literal- und Enum-Werte. Als abgeschlossen gilt, wenn vollständig abgedeckte separate Literal-Overloads keinen redundanten Nicht-Literal-Overload mehr erfordern und das betroffene Dokumentationsbeispiel aktualisiert wurde.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
38/100

Neue Issues direkt in Ihr Postfach

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