I have a function with two parameters that can each take one of two types. Three of the four pairwise combinations are valid, but the fourth is invalid. I’d like to find a way to type hint this scenario that can check these types, but not necessarily have to write code to check for the invalid case every single time I call foo()
. Is there a way I can improve the type hints for either foo()
, bar()
, or both?
In this simplified version of the issue, calling foo()
on two objects that are both of type B
is the only combination that isn’t allowed and would have no meaningful result even if it was.
from typing import Union, overload
class A:
pass
class B:
pass
class C:
pass
class D:
pass
class E:
pass
@overload
def foo(x: A, y: A) -> C: ...
@overload
def foo(x: A, y: B) -> D: ...
@overload
def foo(x: B, y: A) -> E: ...
def foo(x: Union[A, B], y: Union[A, B]) -> Union[C, D, E]:
if isinstance(x, B) and isinstance(y, B):
raise ValueError
raise NotImplementedError
def bar(x: Union[A, B], y: Union[A, B]):
return foo(x, y)
For this code, Pyright gives an error “No overloads for foo match the provided arguments” at return foo(x, y)
.
alexw is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.