python / python/mypy

Incorrect (incomplete) inference for mapping containing types derived from Any

Open
#13,088 0 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

Given a dict literal where the values are (lists of) types which include an Any in their hierarchy as well as a concrete type, the inference is unable to match the values to the side of the inheritance chain that ends in Any. This does not seem to be an issue if the same lists are extracted out of the dict literal and assigned directly to an equivalent variable.

To Reproduce

# Some import that mypy can't follow (perhaps a library which isn't annotated)
import unknown

class FromAny(unknown.Something):
    pass

class Mixin:
    pass

class Concrete1(Mixin, FromAny):
    pass

class Concrete2(Mixin, FromAny):
    pass

values: list[type[FromAny]]

# works ok
values = [Concrete1, Concrete2]

# Error: Incompatible types in assignment (expression has type "List[Type[Mixin]]", variable has type "List[Type[FromAny]]")  [assignment]
values = {
    42: [Concrete1, Concrete2],
}[42]

Your Environment

  • Mypy version used: 0.921, 0.961
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.9

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 issue. Start by running the provided Python reproducer through mypy and trace inference for the dict literal and its indexed value, then add a regression test showing that the concrete classes are accepted as list[type[FromAny]].

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.