Skip to content Skip to sidebar Skip to footer

Python Type Hinting: Function Return Type, Given As Argument, But Type Is Generic Alias Like Union

We can specify easily return type of function, even if type we expect is provided as one of it's argument: from typing import TypeVar, Type, Union T = TypeVar('T') def to(t: Typ

Solution 1:

How about using a "Callable" for the to function, instead of the operator to construct the type?

You could then have a constructor for Union type as argument.

An example of such implementation would be:

from typing import Any, Callable, TypeVar, Type, Union

T = TypeVar('T')
V = TypeVar('V')


def to(t: Callable[[V], T], v: V) -> T:
    return t(v)

G = Union[str, int]

def build_g(v:G) -> G:
    return v if isinstance(v, int) else str(v)


s: str = to(str, 1)
i1: int = to(int, 1)
i2: int = to(str, 1)  # Ok: Expected type 'int', got 'str' instead

g1: G = to(build_g, 1) # No error raised
g2: G = to(build_g, "2") # No error raised

The code above only raises an error in mypy for i2


Post a Comment for "Python Type Hinting: Function Return Type, Given As Argument, But Type Is Generic Alias Like Union"