python / python/mypy

Mypy cannot guess callable return type (`Tuple[Type[T], ...] -> T`)

Open
#17,700 2 comments 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

It looks like mypy cannot detect some types like following type.

To Reproduce

Playground: https://mypy-play.net/?mypy=latest&python=3.12&gist=f83671bbbc02711ac90962ae786b418b

from typing import Union, Type, Tuple, TypeVar

T = TypeVar("T")


def some_types(type_: Union[Type[T], Tuple[Type[T], ...]]) -> T:
    ...

def int_str_float_fn(a: int | str | float) -> None:
    ...

a = some_types((int, str, float))

int_str_float_fn(a)  # should't be an error

I got an error like

main.py:14: error: Argument 1 to "int_str_float_fn" has incompatible type "object"; expected "int | str | float"  [arg-type]

Expected Behavior

No error here.
Screenshot 2024-08-21 at 18 13 42

I think VSCode has a quite good guess here.
Mypy seems guessing a is object.

Actual Behavior

Your Environment

  • Mypy version used: latest
  • Mypy command-line flags: in playground
  • Mypy configuration options from mypy.ini (and other config files): in playground
  • Python version used: 3.12

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 linked mypy-play reproduction and inspect how mypy infers the return type of some_types when passed a heterogeneous tuple of classes. Trace the callable and TypeVar inference path, then add or update a regression test for this example; done means the inferred value is accepted as int | str | float without an argument-type error.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.