I would like to write the following overloaded Python function:
from typing import Any, TypeVar, overload
_T1 = TypeVar('_T1')
_T2 = TypeVar('_T2')
_T3 = TypeVar('_T3')
@overload
def parse_as(ty: type[_T1] | type[_T2], s: bytes) -> _T1 | _T2:
...
@overload
def parse_as(ty: type[_T1] | type[_T2] | type[_T2], s: bytes) -> _T1 | _T2 | _T3:
...
def parse_as(ty: Any, s: bytes) -> Any:
raise NotImplementedError()
The goal of parse_as()
is to attempt to parse the input bytes as the given types and, if successful, return a value of the given types. However this gives the following mypy error:
error: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader
Is there any way to express the type of parse_as()
?
Aside: in my particular case all the TypeVar
s share the same class as their bound
, if that matters.