簡體   English   中英

接受類型並返回給定類型值的函數的Python類型注釋

[英]Python type annotation for a function that accepts a type and returns a value of given type

我正在嘗試對將字符串解析為指定類型的函數進行注釋,並努力尋找一種方法來對返回類型進行注釋以表明這一點。

def parse(s: str, t: type) -> t:
    return t(s)

不用說-> t:不起作用。

我希望使用泛型,但沒有找到一種方法來轉換輸入簽名以提供一些信息來推斷TypeVar 最好的是,我想出了一種奇怪而又混亂的方式來扭曲函數簽名,並且僅僅出於類型提示的目的是不能接受的。

from typing import TypeVar

T = TypeVar('T')


def parse(s: str, to: T) -> T:
    t = type(to)
    return t(s)

有沒有一種方法可以以不修改運行時簽名的方式對此功能進行注釋?

我按照@jonrsharpe的建議使用Type解決了它。

from typing import Type, TypeVar

T = TypeVar('T')


def parse(s: str, t: Type[T]) -> T:
    return t(s)


x = parse('123', int)
x = parse('546', int)  # OK
x = parse('324', float)  # mypy error: Incompatible types in assignment (expression has type "float", variable has type "int")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM