假设我使用类型注释定义了以下函数:
from typing import List
def my_function(input_1: str, input_2: int) -> List[int]:
pass
有没有一种方式可以显示这个函数的注释类型?也许有一个名为 types_of
的函数或类似的东西可以使用,例如:
>> types_of(my_function)
[str, int] -> [List[int]]
假设我使用类型注释定义了以下函数:
from typing import List
def my_function(input_1: str, input_2: int) -> List[int]:
pass
有没有一种方式可以显示这个函数的注释类型?也许有一个名为 types_of
的函数或类似的东西可以使用,例如:
>> types_of(my_function)
[str, int] -> [List[int]]
__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]}
或者您可以使用来自typing
模块的get_type_hints
函数。实际上,我认为这是更合适的解决方案。
根据文档,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]}
对于类,get_type_hints
返回一个字典,该字典由沿着Foo.__mro__
反向合并所有__annotations__
构成。
class Bar:
BAR_C: bool = True
class Foo(Bar):
FOO_STR: str = 'foo'
FOO_INT: int = 42
def __init__(a: str, b: int) -> None:
self._a = a
self._b = b
def some_method(self, foo: List, bar: bool) -> bool:
pass
In [7]: get_type_hints(Foo)
Out[7]: {'BAR_C': bool, 'FOO_STR': str, 'FOO_INT': int}
Out[8]: get_type_hints(Foo.__init__)
Out[8]: {'a': str, 'b': int, 'return': NoneType}
In [9]: get_type_hints(Foo.some_method)
Out[9]: {'foo': typing.List, 'bar': bool, 'return': bool}
我们的模块是 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()
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}
inspect
模块:import inspect
from typing import List
def my_function(input_1: str, input_2: int) -> List[int]:
pass
def types_of(func):
specs = inspect.getfullargspec(func)
return_type = specs.annotations['return']
input_types = [t.__name__ for s, t in specs.annotations.items() if s != 'return']
return f'[{", ".join(input_types)}] -> {return_type}'
types_of(my_function)
输出:
'[str, int] -> typing.List[int]'
你可以使用 inspect
import inspect
def sum_numbers(first_number=4,second_number=5):
return a+b
def print_argtypes(function):
specs = inspect.getfullargspec(sum_numbers)
for s in range(len(specs[0])):
print(specs[0][s]+': '+str(type(specs[3][s])))
print_argtypes(sum_numbers)
输出
first_number: <class 'int'>
second_number: <class 'int'>
get_type_hints
对于装饰器函数也适用,但实际上它只返回外部的类型。 - Max