Inconsistent processing Literal as TypeVar
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- Ø Merge
- 1 T. 18 Std.
- Gemergte PRs (30 T.)
- 54
Beschreibung
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
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
Beginne mit dem bereitgestellten Python-3.12-Reproducer unter --strict und vergleiche die reveal_type-Ergebnisse für die beiden Aufrufe. Verfolge die Typinferenz bei generischen Aufrufen und die Behandlung von Literal; abgeschlossen ist die Aufgabe, wenn das beabsichtigte Verhalten vereinbart und durch einen Regressionstest abgedeckt ist, einschließlich der Frage, ob der explizite Cast weiterhin redundant ist.
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
- 35/100