简体   繁体   English

类型提示以返回类型为参数的 function

[英]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?有没有办法输入一个 function 作为参数的返回类型? 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.但它不起作用。

Have a look at Generics , especially TypeVar .看看Generics ,尤其是TypeVar You can do something like this:你可以这样做:

from typing import TypeVar, Any

T = TypeVar("T")

def mycoerce(data: Any, ret_type: T) -> T:
    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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM