Overloading a function with a parameter that can be either SomeType[Any] or Any always results in the return type Any

Open
#10,752 9 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

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

Research direction

Start with the overload examples in the issue and trace how mypy selects between a SomeType[Any]-like overload and an Any overload. Compare the Callable/Any case with the int/Any and Callable/int cases, then verify that the corrected behavior reports the incompatible assignment while preserving the existing contrasting cases.

Written by the indexing model from the issue text.

Description

Edit: I initially observed this behaviour for Callable[..., Any] and Any, but it now seems like this happens for any SomeType[Any] and Any, hence we've edited the title. For a more extensive explanation, scroll down to post 8.


I noticed that overloading a function with a Callable / Any parameter doesn't work as I'd expect. For example:

from typing import Any, Callable, overload

@overload
def foo(a: Callable) -> int: ...
@overload
def foo(a: Any) -> Any: ...

def foo(a):
    pass

a: str = foo(lambda x: x)

I'd expect the mypy error Incompatible types in assignment (expression has type "int", variable has type "str"), but there's no error here.

Of note, if I replace Callable by something else, it works fine:

from typing import Any, overload

@overload
def foo(a: int) -> int: ...
@overload
def foo(a: Any) -> Any: ...

def foo(a):
    pass

a: str = foo(1)
# mypy error: Incompatible types in assignment (expression has type "int", variable has type "str")

Finally, if I instead replace Any by something else, it also works fine.

from typing import Any, Callable, overload

@overload
def foo(a: Callable) -> int: ...
@overload
def foo(a: int) -> Any: ...

def foo(a):
    pass

a: str = foo(lambda x: x)
# mypy error: Incompatible types in assignment (expression has type "int", variable has type "str")

So it only doesn't work as expected in the first code block. Is that a bug? Or is it expected behaviour somehow?

Dominant language
Python
Stars
20.6k
Forks
3.3k
Avg merge
1d 18h
Merged PRs (30d)
54

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.

More from python/mypy

All issues in python/mypy

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.