【问题标题】:Get Union values from function annotations?从函数注释中获取联合值?
【发布时间】:2021-08-28 23:05:27
【问题描述】:

我正在寻找函数的注释,特别是每个注释的联合值。举个例子:

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__ 返回字典,但我不确定 Union 类型提示

【问题讨论】:

    标签: python annotations python-typing


    【解决方案1】:

    使用typing.get_args:

    >>> func.__annotations__['arg3']
    typing.Union[str, int]
    >>> from typing import get_args
    >>> get_args(func.__annotations__['arg3'])
    (<class 'str'>, <class 'int'>)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-07
      • 1970-01-01
      • 1970-01-01
      • 2017-04-19
      • 2020-05-18
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      相关资源
      最近更新 更多