python / python/mypy

Strange type expected from inferred dict

Open
#14,499 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

Strange inference with dict.

To Reproduce

The repro is found in this Mypy playground, but here it is for convenience:

import random

value: str|None = None

if random.random() > 0.5:
    my_dict = {'a': False, 'b': None}
else:
    my_dict = {'a': True, 'b': value}

Expected Behavior

No error.

Actual Behavior

Error: main.py:8: error: Dict entry 1 has incompatible type "str": "Optional[str]"; expected "str": "Optional[bool]" [dict-item

Your Environment

  • Mypy version used: 0.911
  • Python version used: 3.11

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 linked mypy playground repro and compare the inferred types for the two dictionary literals. Trace the dictionary type-inference path that produces the dict-item error, then add a regression test showing that this example type-checks without an 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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.