When using type hints in python
with mypy
, I often encounter the error Overload function overlap with incompatible return types
. I am trying to better understand, how mypy matches which overload function and in that regards, I have the following piece of code:
from typing import Literal, overload
@overload
def foo(x: str, y: str, z: Literal[True]) -> int: ...
@overload
def foo(x: str, y: str, z: Literal[False]) -> str: ...
@overload
def foo(x: str = ..., y: str = ..., z: Literal[False] = ...) -> str: ...
@overload
def foo(*, x: str = ..., y: str = ..., z: Literal[True]) -> int: ...
def foo(x: str = "a", y: str = "b", z: bool = False) -> str | int:
if z:
return 1
else:
return x + y
foo() # matches 3rd overload
foo(z=True) # matches 4th overload
foo(z=False) # matches 3rd overload
foo(x="a", z=True) # matches 4th overload
foo("a", "b", True) # matches 1st overload
foo(x="a", z=False) # matches 3rd overload
foo("a", "b", False) # matches 2nd overload
foo("a", y="b", z=True) # matches 4th overload
foo("a", y="c", z=False) # matches 3rd overload
This piece of code doesn’t fail with mypy. However, I am not sure if I am able to infer correctly which overload function is matching to which invocation (although, I have added comments, but most likely they are incorrect)
Is it possible to see, which overload function mypy
is picking, when the function is invoked?