python / python/mypy

Inconsistent behavior with Literals depending on the amount of elements it contains

Open
#9,099 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic-join-v-union topic-literal-types
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

This is an issue I ran into working on #9097.
Code adapted from this test.

Literals with one value:

from typing import List
from typing_extensions import Literal

lit1: Literal[1]
lit2: Literal[2]

arr2 = [lit1, lit2]

reveal_type(arr2)
➜  mypy git:(master) python3 -m mypy leba_misc/test2.py
leba_misc/test2.py:9: note: Revealed type is 'builtins.list[builtins.int*]'

Literals with multiple values:

from typing import List
from typing_extensions import Literal

lit1: Literal[1]
lit2: Literal[2, 3]

arr2 = [lit1, lit2]

reveal_type(arr2)
➜  mypy git:(master) python3 -m mypy leba_misc/test2.py
leba_misc/test2.py:9: note: Revealed type is 'builtins.list[Union[Literal[1], Literal[2], Literal[3]]]'

On Python 3.7 and mypy 0.790.

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 by running the issue's two reproduction snippets with mypy and compare them with test-data/unit/check-literal.test around the linked case. Trace the revealed-type behavior for list inference involving Literal values, then add or update a regression test so the one-value and multi-value cases behave consistently.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.