从函数注释中获取联合值?
Get Union values from function annotations?
我正在寻找函数的注释,特别是每个注释的 Union 值。让我举个例子:
from typing import Union
async def func(arg1: str, arg2: int, arg3: Union[str, int]):
...
# Want to get
# {arg3: [str, int], arg1: str, ...}
我知道 func.__annotations__
returns 字典,但我不确定 Union 类型提示
使用typing.get_args
:
>>> func.__annotations__['arg3']
typing.Union[str, int]
>>> from typing import get_args
>>> get_args(func.__annotations__['arg3'])
(<class 'str'>, <class 'int'>)
我正在寻找函数的注释,特别是每个注释的 Union 值。让我举个例子:
from typing import Union
async def func(arg1: str, arg2: int, arg3: Union[str, int]):
...
# Want to get
# {arg3: [str, int], arg1: str, ...}
我知道 func.__annotations__
returns 字典,但我不确定 Union 类型提示
使用typing.get_args
:
>>> func.__annotations__['arg3']
typing.Union[str, int]
>>> from typing import get_args
>>> get_args(func.__annotations__['arg3'])
(<class 'str'>, <class 'int'>)