python / python/mypy

Odd behavior with overload and `Any` arguments.

Open
#15,452 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
The behavior of overload is not properly matching when one of the arguments is Any.

See https://github.com/microsoft/pyright/issues/5216#issuecomment-1594046589

To Reproduce

from typing import Any, Literal, TypeVar, overload

_T = TypeVar("_T")

class A:
    @overload
    def method1(self, k: Literal["hi"], default: Any) -> float:
        ...

    @overload
    def method1(self, k: str, default: _T) -> Any | _T:
        ...

    def method1(self, k: str, default: _T) -> Any | _T:
        ...

def func(a: A, b: list, c: Any):
    v1 = a.method1("hi", [])
    reveal_type(v1)  # mypy: float

    my_list1: list = []
    v2 = a.method1("hi", my_list1)
    reveal_type(v2)  # mypy: Any

    v3 = a.method1("hi", b)
    reveal_type(v3)  # mypy: Any

    v4 = a.method1("hi", c)
    reveal_type(v4)  # mypy: Any

    my_list2: list[int] = []
    v5 = a.method1("hi", my_list2)
    reveal_type(v5)  # mypy: float```

**Expected Behavior**

All of the revealed types should have been `float`, since the first argument of each call to `method1()` is `"hi"`.  This is the behavior of `pyright`, which seems to make more sense.

**Actual Behavior**
```text
overload.py:19: note: Revealed type is "builtins.float"
overload.py:23: note: Revealed type is "Any"
overload.py:26: note: Revealed type is "Any"
overload.py:29: note: Revealed type is "Any"
overload.py:33: note: Revealed type is "builtins.float"

Your Environment

  • Mypy version used: 1.3
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.10

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 supplied Python reproducer with mypy 1.3 and inspect the revealed types for each overload call. Trace overload matching for Literal["hi"] when the second argument is Any or an unparameterized list; done means all five calls reveal float as expected.

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.