簡體   English   中英

類型提示以返回類型為參數的 function

[英]type hinting a function that takes the return type as parameter

有沒有辦法輸入一個 function 作為參數的返回類型? 我天真地嘗試這樣做:

# 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 ,尤其是TypeVar 你可以這樣做:

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