Is there a way to type hint a function that takes as argument its return type? I naively tried to do this:
JavaScript
x
12
12
1
# NOTE:
2
# This code does not work!
3
#
4
# If I define `ret_type = TypeVar("ret_type")` it becomes syntactically
5
# correct, but type hinting is still broken.
6
#
7
def mycoerce(data: Any, ret_type: type) -> ret_type
8
return ret_type(data)
9
10
a = mycoerce("123", int) # desired: a type hinted to int
11
b = mycoerce("123", float) # desired: b type hinted to float
12
but it doesn’t work.
Advertisement
Answer
Have a look at Generics, especially TypeVar. You can do something like this:
JavaScript
1
13
13
1
from typing import TypeVar, Callable
2
3
R = TypeVar("R")
4
D = TypeVar("D")
5
6
def mycoerce(data: D, ret_type: Callable[[D], R]) -> R:
7
return ret_type(data)
8
9
a = mycoerce("123", int) # desired: a type hinted to int
10
b = mycoerce("123", float) # desired: b type hinted to float
11
12
print(a, b)
13