接受类型并返回给定类型值的函数的Python类型注释

时间:2019-04-23 21:52:47

标签: python-3.x python-typing

我正在尝试对将字符串解析为指定类型的函数进行注释,并努力寻找一种方法来对返回类型进行注释以表明这一点。

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)

是否有一种方法可以以不修改运行时签名的方式对此功能进行注释?

1 个答案:

答案 0 :(得分:0)

我按照@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")