如何获取函数参数类型?
How to get function arguments type?
例如我有 foo(...)
:
def foo(arg1: str, arg2: int, ...):
...
我想得到这个:
{'arg1': str, 'arg2': int, ...}
如果有人知道答案,请与我分享。
这可以通过函数对象的 __annotations__
属性访问 Python 版本 >= 3.0:
type_annotation_dict = foo.__annotations__
这应该直接导致字典将参数名称映射到它们的类型注释:
{'arg1': str, 'arg2': int}
另见 PEP 3107。
此外,typing
标准库模块有一个函数 get_type_hints
,它提供了一些额外的功能。有关详细信息,请参阅 the Python docs on this function。
例如我有 foo(...)
:
def foo(arg1: str, arg2: int, ...):
...
我想得到这个:
{'arg1': str, 'arg2': int, ...}
如果有人知道答案,请与我分享。
这可以通过函数对象的 __annotations__
属性访问 Python 版本 >= 3.0:
type_annotation_dict = foo.__annotations__
这应该直接导致字典将参数名称映射到它们的类型注释:
{'arg1': str, 'arg2': int}
另见 PEP 3107。
此外,typing
标准库模块有一个函数 get_type_hints
,它提供了一些额外的功能。有关详细信息,请参阅 the Python docs on this function。