GeezerVison is showing github.com — Inconsistent processing Literal as TypeVar · Issue #19761 · python/mypy
Inconsistent processing Literal as TypeVar #19761Description
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
ActivityA5rocks commented on Aug 30, 2025 This is because we figure you probably want a str there. For instance, under a strict application of this logic, [5] would be a list that can only contain 5. That's probably not what you mean! (it's heuristics all the way down)
However, it's possible for mypy not to warn about redundant-cast I think. Reacted by Stanislav Terliakov and Evgeniy Slobodkin A5rocks commented on Aug 30, 2025 I looked at this a bit, this is because cast is checking whether the target (Literal['a']) and the source (Literal['a']?, i.e. str known to be a 'a') are the same type, but not whether they're functionally the same type. I experimented with setting Literal['a']? as not a subtype of Literal['a'] (because it is a str instance), but that causes test failures and seems wrong anyways.
@asottile I see you made the change to is_same_type, do you have an intuition for what we should do here? My instinct is add some special casing for literals for casts, but that sucks! asottile commented on Sep 6, 2025 yeah I think the interesting part here is it is a redundant cast (Literal['a'] and Literal['a']? are "the same") but the problem is that other parts of the system involved treat those two differently (TypeVar handling treats Literal['a']? as str)
not sure there's a good answer since contextually it's either right or wrong randolf-scholz commented on Dec 20, 2025
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|