python / python/mypy

Inconsistent processing Literal as TypeVar

Open
#19,761 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-casts topic-type-context
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.