python / python/mypy

mypy recognizes value type in nested dicts as object

Open
#13,374 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

In some cases (see code below) mypy recognizes type of values in nested dict as object. Adding hint with more exact type results in an error.

To Reproduce

from typing import Union

key = 'foo'
x: dict[str, Union[str, bool]] = {
    'foo': {
        'key1': 'value',
        'key2': True,
    },
    'bar': {
        'key3': 'value',
        'key4': False,
    },
}[key]

Expected Behavior

mypy should not raise any error.

Actual Behavior

main.py:4: error: Incompatible types in assignment (expression has type "Dict[str, object]", variable has type "Dict[str, Union[str, bool]]")
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.971
  • Python version used: 3.11
  • Operating system: Linux

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 nested-dictionary reproducer in main.py and run mypy against it using the reported Python and mypy versions. Trace the type inference for the dictionary literal and indexed lookup; done means the example produces no error while retaining the expected dict[str, Union[str, bool]] type.

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.