如何在Python中打印函数的类型注释?

6

假设我使用类型注释定义了以下函数:

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]]
3个回答

9
您可以使用__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()

那么,让我们打开 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}

1
简单明了 - 很好!这对类和装饰器也适用吗? - winklerrr
1
get_type_hints 对于装饰器函数也适用,但实际上它只返回外部的类型。 - Max

2
你可以使用 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]'

1

你可以使用 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'>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接