Skip to content
Advertisement

type hinting a function that takes the return type as parameter

Is there a way to type hint a function that takes as argument its return type? I naively tried to do this:

# NOTE:
# This code does not work!
#
# If I define `ret_type = TypeVar("ret_type")` it becomes syntactically 
# correct, but type hinting is still broken.
#
def mycoerce(data: Any, ret_type: type) -> ret_type
    return ret_type(data)

a = mycoerce("123", int)  # desired: a type hinted to int
b = mycoerce("123", float)  # desired: b type hinted to float

but it doesn’t work.

Advertisement

Answer

Have a look at Generics, especially TypeVar. You can do something like this:

from typing import TypeVar, Callable

R = TypeVar("R")
D = TypeVar("D")

def mycoerce(data: D, ret_type: Callable[[D], R]) -> R:
    return ret_type(data)

a = mycoerce("123", int)  # desired: a type hinted to int
b = mycoerce("123", float)  # desired: b type hinted to float

print(a, b)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement