python / python/mypy

Dict update typing error, update Dict[Union[int, str], str] from Dict[int, str]

Open
#16,072 1 comment 2 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

To Reproduce

from typing import Dict, Union

dict_a: Dict[Union[int, str], int] = {}
dict_b: Dict[int, int] = {}
dict_a.update(dict_b)
print(dict_a)

Expected Behavior

No mypy error. dict_b has stricter typing than dict_a, this update operation should be fine.
Actual Behavior

error: Argument 1 to "update" of "MutableMapping" has incompatible type "dict[int, int]"; expected "SupportsKeysAndGetItem[Union[int, str], int]"  [arg-type]

Your Environment

  • Mypy version used: 1.5.1 (compiled: yes)
  • Python version used: 3.9.16

Other Notes
updating items iteratively apparently has no issue.

from typing import Dict, Union

dict_a: Dict[Union[int, str], int] = {}
dict_b: Dict[int, int] = {}
for k, v in dict_b.items():
    dict_b[k] = v
print(dict_a)

Using Any of course has no issue too.

from typing import Any, Dict

dict_a: Dict[Any, int] = {}
dict_b: Dict[int, int] = {}
dict_a.update(dict_b)
print(dict_a)

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 Python reproduction with mypy 1.5.1 and compare the reported update error with the iterative update example. Trace the typing used for MutableMapping.update and add a regression test showing that dict[int, int] can update Dict[Union[int, str], int] 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.