类型提示以 return 类型作为参数的函数

type hinting a function that takes the return type as parameter

有没有一种方法可以键入提示函数,该函数将其 return 类型作为参数?我天真地尝试这样做:

# 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

但是没用。

看看Generics, especially TypeVar。你可以这样做:

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)