python / python/mypy

Improve generic arguments inference for overloads

Open
#15,750 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Feature

In the following example (https://mypy-play.net/?mypy=latest&python=3.11&gist=3119048d3a61ecdda21806b02a0bd08c)

from typing import Any, Mapping, TypeVar, overload

_KT = TypeVar("_KT")
_VT = TypeVar("_VT")
_T1 = TypeVar("_T1")
_T2 = TypeVar("_T2")

class D(Mapping[_KT, _VT]):
    @overload
    def foo(self, value: Mapping[_KT, _VT]) -> D[_KT, _VT]: ...
    @overload
    def foo(self, value: Mapping[_T1, _T2]) -> D[_KT | _T1, _VT | _T2]: ...

    def foo(self, value: Any) -> Any:
        return self

def test(d: D[str, int]) -> None:
    d2: dict[str, Any] = {}
    reveal_type(d.foo(d2))
    d3: dict[int, Any] = {}
    reveal_type(d.foo(d3))

the types are revealed as

main.py:19: note: Revealed type is "__main__.D[Any, Any]"
main.py:21: note: Revealed type is "__main__.D[Union[builtins.str, builtins.int], Union[builtins.int, Any]]"
  1. The first one can be improved to D[str, Any] since both overloads return D[str, ...].
  2. For the second one, is there any point in infering Union[int, Any] instead of just Any? This is probably a general question, but I couldn't find any issues about it. Is there any context in which Union[int, Any] provides any extra information?

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 with the linked mypy-play example and compare the revealed types for the two overload calls. Investigate how generic arguments are inferred across overloads and how unions containing Any are represented; done means the first result preserves str and the second does not retain redundant Union[int, Any] information.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.