Inconsistent processing Literal as TypeVar
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
Without an explicit cast to Literal mypy infers TypeVar as str (instead of Literal['a']) in the example below. But with an explicit cast, we have a redundant-cast error.
To Reproduce
import typing as tp
def foo[T](x: T) -> T: ...
a1 = foo('a')
a2 = foo(tp.cast(tp.Literal['a'], 'a'))
reveal_type(a1) # Revealed type is "builtins.str"
reveal_type(a2) # Revealed type is "Literal['a']"
https://mypy-play.net/?mypy=latest&python=3.12&flags=strict&gist=d58b88feb5b5ab8d53b3a566b15b5f03
It looks inconsistent, because if we run reveal_type('a') we'll get Literal['a']?, so why couldn't we use Literal['a'] as a return type? I didn't find this moment in typing spec or in the PEP, so probably, this behavior is not specified.
Other type checkers have different behavior (links for playground are given in brackets):
Your Environment
- Mypy version used: 1.17.1
- Mypy command-line flags:
--strict - Mypy configuration options from
mypy.ini(and other config files): - - Python version used: 3.12
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
Inizia con il riproduttore Python 3.12 fornito usando --strict e confronta i risultati di reveal_type per le due chiamate. Traccia l’inferenza dei tipi nelle chiamate generiche e la gestione di Literal; il lavoro è completo quando il comportamento previsto è concordato e coperto da un test di regressione, incluso stabilire se il cast esplicito rimane ridondante.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100