Overloading a function with a parameter that can be either SomeType[Any] or Any always results in the return type Any
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
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?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
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.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100