python / python/mypy

`dict(...)` hides incompatible assignment when source has `Any` key type

Open
#10,530 1 comment 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

Using dict(...) around an otherwise incompatible mapping structure leads mypy to omit errors about the type incompatibility. My original code called dict on a collections.defaultdict, though that doesn't seem to be required to reproduce this.

To Reproduce

from typing import Any, Dict

foo: Dict[str, str]
bar: Dict[Any, int] = {}
foo = bar  # Incompatible types in assignment (expected, correct)
foo = dict(bar)  # no error (unexpected, IMO incorrect)

This seems to be related to the fact that the key type is Any. Changing the key to int causes an error on both assignment lines (even if the value type is Any).

Your Environment

  • Mypy version used: 0.812
  • Mypy command-line flags: none needed, though notable that --strict doesn't affect this
  • Python version used: 3.7.10
  • Operating system and version: Ubuntu 20.04

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

No source file or test is named in the report. Start by running the provided reproduction with mypy 0.812, then trace how dict(...) infers mappings when the source key type is Any. Add a regression test covering the reported assignment and verify that the incompatible assignment is diagnosed.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 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.