python-3.x - 用于类型注解的 Python 类型注解
问题描述
我的问题是:当函数将类型注释作为参数时,您使用什么类型注释?
为什么我将类型注释作为参数?
我有一个函数试图根据类型注释解析字符串。例如
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)
我想输入注释这个函数。
解决方案
通过一些调查,我们可以检测出类似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
来表明你使用类型别名,我没有工具来查看 linter 是否确认了这一点。