Inconsistent processing Literal as TypeVar
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the supplied Python 3.12 reproducer under --strict and compare the reveal_type results for the two calls. Trace generic-call type inference and Literal handling; done means the intended behavior is agreed and covered by a regression test, including whether the explicit cast remains redundant.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100