Narrowing argument types based on overload variants in MyPy

Viewed 234

I have the following code, for which I have no idea how to avoid the issue with narrowing down function arguments based on function's overload variants:

from typing import Union
from typing import Callable
from typing import overload

class A:
    pass

class B:
    pass

class C:
    pass

class D:
    pass

@overload
def f(x: A) -> C:...

@overload
def f(x: B) -> D:...

def f(x: Union[A, B]) -> Union[C, D]:
    if isinstance(x, A):
        return C()
    else:
        return D()

@overload
def g(x: A, func: Callable[[C], bool]) -> None:...

@overload
def g(x: B, func: Callable[[D], bool]) -> None:...

def g(x: Union[A, B], func: Union[Callable[[C], bool], Callable[[D], bool]]) -> None:
    obj = f(x)
    func(obj)

The code results in the following error message:

test.py:37: error: Argument 1 has incompatible type "Union[C, D]"; expected "C"
test.py:37: error: Argument 1 has incompatible type "Union[C, D]"; expected "D"

Is there a way to overcome this issue with MyPy not being able to narrow down argument types based on the overload variants?

0 Answers
Related