Eager narrowing to `Literal` when possible
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
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.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Riproduci i tre esempi letter_v1, letter_v2 e letter_v3 usando il caso mypy-play collegato, quindi traccia il modo in cui mypy inferisce i tipi delle variabili locali. Determina il comportamento di narrowing previsto e aggiungi una copertura di regressione per gli esempi; il lavoro è completato quando le funzioni annotate superano il controllo dei tipi senza tipi espliciti per letter.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- compilers
- Tipo di issue
- Funzionalità
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100