Eager narrowing to `Literal` when possible
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Feature
I often feel I have to put too much effort into informing mypy that some variables can only hold a finite set of values. It would be helpful if mypy was a bit smarter in the way it infers Literal types.
Pitch
Here are some concrete examples:
from typing import Literal
def letter_v1(number: int) -> Literal["a", "b", "c"]:
if number == 1:
letter = "a"
elif number == 2:
letter = "b"
else:
letter = "c"
# Incompatible return value type (got "str", expected "Literal['a', 'b', 'c']") [return-value]
return letter
def letter_v2(number: int) -> Literal["a", "b", "c"]:
letter = "a" if number == 1 else "b" if number == 2 else "c"
# Incompatible return value type (got "str", expected "Literal['a', 'b', 'c']") [return-value]
return letter
def letter_v3(number: int) -> Literal["a", "b", "c"]:
letter = ("a", "b", "c")[number]
# Incompatible return value type (got "str", expected "Literal['a', 'b', 'c']") [return-value]
return letter
See also: https://mypy-play.net/?mypy=1.3.0&python=3.11&flags=strict&gist=bab569e05877621b90f081fc7bdb7d05
Ideally, I think I should get away without having to specify the type of letter in any of the concrete examples here. A human reviewing this code would easily conclude that there is no issue here, yet mypy struggles.
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Reproduziere die drei letter_v1, letter_v2 und letter_v3 Beispiele anhand des verlinkten mypy-play-Falls und verfolge anschließend, wie mypy die Typen der lokalen Variablen ableitet. Bestimme das beabsichtigte Narrowing-Verhalten und füge Regressionstestabdeckung für die Beispiele hinzu; als erledigt gilt die Aufgabe, wenn die annotierten Funktionen ohne explizite Typen für letter die Typprüfung bestehen.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers
- Issue-Typ
- Feature
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100