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

标签 python python-3.x

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

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 函数。实际上我认为这是更合适的解决方案

根据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]}

类示例:

对于一个类,get_type_hints 返回一个字典,该字典通过将所有 __annotations__ 沿着 Foo.__mro__ 以相反的顺序合并而构造。

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}

关于python - 如何在 Python 中打印函数的类型注释?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57109996/

相关文章:

python - 如何使用groupby选择条件行?

绝对初学者的Python编程第5章挑战4

python-3.x - 运行 virtualenv 时出现 FileNotFoundError

Python:登录后无法删除文件

python - 尝试合并 2 个数据帧但得到 ValueError

netbeans - Netbeans 6.9.1中Python3项目调试

python - 使用 Python 打开文件

python - 有没有办法对多次执行的代码块进行计时?

python - 不使用 len 运算符查找列表的长度

python - Vertex AI 预定笔记本不起作用,但手动工作