python / python/mypy

Mypy fails to correctly validate Type[T]

Open
#8,681 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

topic-type-variables
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Dear all,

Consider the example code below:

from typing import Type, TypeVar, Tuple

T = TypeVar('T')


def func(a: T, a_type: Type[T]) -> Tuple[T, Type[T]]:
    return a, a_type


a1, a1_type = func(1, int)
a2, a2_type = func(1, str)

reveal_type(a1)
reveal_type(a1_type)
reveal_type(a2)
reveal_type(a2_type)

The first call to func shouldn't give rise to any issues, while the second one should complain about an incompatible type in the a_type argument (as type(1) is not str).

Yet, whenever I run mypy (Python 3.7; mypy 0.770; MacOS 10.15.1) it fails to produce any errors, even going as far to infer the type of a2 as object instead of int.

>>> mypy test.py
test.py:13: note: Revealed type is 'builtins.int'
test.py:14: note: Revealed type is 'Type[builtins.int]'
test.py:15: note: Revealed type is 'builtins.object'
test.py:16: note: Revealed type is 'Type[builtins.object]'

Is anyone familiar with this issue?

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 provided example with mypy and comparing the reported types and diagnostics with the expected result. Trace the type inference and argument validation path for Type[T]; done means rejecting func(1, str), accepting func(1, int), and inferring the revealed types correctly.

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
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.