用于类型注释的Python类型注释

时间:2020-08-19 19:58:30

标签: python-3.x

我的问题是:当函数将类型注释用作参数时,您使用什么类型注释?

我为什么要以类型注释作为参数?

我有一个函数尝试根据类型注释解析字符串。例如

def get_appropriate_type_converter(type_annotation) -> Callable[[str], 'type_annotation']:

例如get_appropriate_type_converter(Dict[str, int])("aaa:3,bbb:4") == dict(aaa=3, bbb=4)

我想输入此功能的注释。

1 个答案:

答案 0 :(得分:4)

通过一些调查,我们可以发现类似Dict[str,int]的类型是

>>> from typing import *
>>> x = Dict[str, int]
>>> type(x)
<class 'typing._GenericAlias'>
>>> y = Union[str, float]
>>> type(y)
<class 'typing._GenericAlias'>

所以我的猜测是,您将使用注释typing._GenericAlias来表示您使用类型别名,但我没有工具来查看短绒毛是否可以确认这一点。

相关问题