python / python/mypy

Union types for dict keys are not inferred in union context

Open
#6,079 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug false-positive needs discussion priority-1-normal topic-join-v-union topic-union-types
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

mypy: 0.650
Python: 3.7.1

I'm not sure if this is a bug or a new feature, however the following code is unexpected (in my mind, especially coming from TypeScript):

d = {"1": 2, 3: 4}
reveal_type(d)  # builtins.dict[builtins.object*, builtins.int*]

I would have expected mypy to infer the type of d as builtins.dict[Union[builtins.str*, builtins.int*], builtins.int*].

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 reproducing the reported dictionary inference with mypy 0.650 and Python 3.7.1, then trace the type inference entry point for dictionary literals. Done means the example reports a dictionary whose key type is a union of str and int, with a regression test covering the behavior.

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.