python / python/mypy

Dict comprehension from Iterable of Literal

Open
#7,814 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive priority-1-normal topic-literal-types
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Related to #7533
mypy 0.740, python 3.7.4, typing_extensions 3.7.4

dict comprehension won't recognize an Iterable of Literal as input.
Unlike in #7533, this is not limited to just tuples.

The dict constructor and dict.fromkeys have no problem.

from typing import Dict
from typing_extensions import Literal

T = Literal[1, 2, 3]
d: Dict[T, None]

d = {x: None for x in [1, 2, 3]}
# error: Key expression in dictionary comprehension has incompatible type "int"; expected type "Union[Literal[1], Literal[2], Literal[3]]"

d = dict(zip([1, 2, 3], [None, None, None]))  # no error
d = dict.fromkeys([1, 2, 3])  # no error

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 reproducer and compare the dict comprehension with the working dict constructor and dict.fromkeys cases. Done means mypy accepts the comprehension assigning literal keys to Dict[Literal[1, 2, 3], None] without the incompatible key-expression error.

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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.