Mypy doesn't recognize that different string literals in if/else statement match a union of string literals
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
Bug Report
When a function has a type signature like def foo(bar: Literal["a", "b"]) -> None: ... mypy throws an error if the argument passed in can be either a or b as it implies a general string.
To Reproduce
from typing import Literal
CHOICE = bool(...)
def foo(bar: Literal["a", "b"]) -> None: ...
def main() -> None:
bar = "a"
if CHOICE:
bar = "b"
foo(bar)
Expected Behavior
It would be nice if mypy recognized that bar here could only be Literal["a"] or Literal["b"], i.e Literal["a", "b"].
Actual Behavior
mre.py:12: error: Argument 1 to "foo" has incompatible type "str"; expected "Literal['a', 'b']" [arg-type]
Your Environment
- Mypy version used: 1.14.1
- Mypy command-line flags: Default
- Mypy configuration options from
mypy.ini(and other config files): Default - Python version used: 3.13
Context
This came up because of a recent change in typeshed https://github.com/python/typeshed/pull/12181 which causes this pip code to trigger a mypy error: https://github.com/pypa/pip/blob/24.3.1/src/pip/_internal/utils/unpacking.py#L179
I assume this issue of different implicit Literal / str types inside branches has been discussed before but I couldn't find it searching through the GitHub issues.
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 la diagnostica in mre.py con mypy 1.14.1 usando l’esempio mostrato di assegnazione in un branch, quindi traccia il modo in cui il type checker inferisce bar nei percorsi if/else. Usa il riferimento pip unpacking.py come caso del mondo reale; il lavoro è completato quando entrambi gli esempi accettano l’unione di string literal senza un errore incompatible-type.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- compilers
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Tranquilla
- Chiarezza
- Specificata chiaramente
- Idoneità per principianti
- 52/100