-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Open
Labels
bugmypy got something wrongmypy got something wrongtopic-caststopic-type-contextType context / bidirectional inferenceType context / bidirectional inference
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
Metadata
Metadata
Assignees
Labels
bugmypy got something wrongmypy got something wrongtopic-caststopic-type-contextType context / bidirectional inferenceType context / bidirectional inference