假设我定义了以下带有类型注释的函数:
from typing import List
def my_function(input_1: str, input_2: int) -> List[int]:
pass
Run Code Online (Sandbox Code Playgroud)
有没有办法显示此函数的注释类型?也许是功能types_of或类似的东西?这样就可以像这样使用它:
>> types_of(my_function)
[str, int] -> [List[int]]
Run Code Online (Sandbox Code Playgroud)
您可以使用 __annotations__
from typing import List
def my_function(input_1: str, input_2: int) -> List[int]:
pass
In [2]: my_function.__annotations__
Out[2]: {'input_1': str, 'input_2': int, 'return': typing.List[int]}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用模块中的get_type_hints功能typing。实际上我认为这是更合适的解决方案。
根据docs get_type_hints返回的字典,其中包含函数,方法,模块或类对象的类型提示。
from typing import get_type_hints, List
def my_function(input_1: str, input_2: int) -> List[int]:
pass
In [2]: get_type_hints(my_function)
Out[2]: {'input_1': str, 'input_2': int, 'return': typing.List[int]}
Run Code Online (Sandbox Code Playgroud)
对于类get_type_hints返回通过合并所有的构造一个字典__annotations__沿着Foo.__mro__以相反的顺序。
from typing import List
def my_function(input_1: str, input_2: int) -> List[int]:
pass
In [2]: my_function.__annotations__
Out[2]: {'input_1': str, 'input_2': int, 'return': typing.List[int]}
Run Code Online (Sandbox Code Playgroud)
我们的模块 test_module.py
from typing import Dict
SOME_CONSTANT: Dict[str, str] = {
'1': 1,
'2': 2
}
class A:
b: str = 'b'
c: int = 'c'
def main() -> None:
pass
if __name__ == '__main__':
main()
Run Code Online (Sandbox Code Playgroud)
然后打开python shell:
In [1]: from typing import get_type_hints
In [2]: import test_module
In [3]: get_type_hints(test_module)
Out[3]: {'SOME_CONSTANT': typing.Dict[str, str]}
In [4]: get_type_hints(test_module.A)
Out[4]: {'b': str, 'c': int}
In [5]: get_type_hints(test_module.main)
Out[5]: {'return': NoneType}
Run Code Online (Sandbox Code Playgroud)