You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Python函数注解中提取Union类型包含的所有子类型?

Python函数注解Union类型解析方法

要解析函数注解里的Union类型,可使用Python标准库typing模块提供的get_origin、get_args工具函数(Python 3.8及以上版本支持),这两个函数可以统一识别传统Union写法和Python 3.10+新增的|联合类型写法。

完整实现代码

from typing import Union, get_origin, get_args
import types

def parse_annotations(func):
    parsed_result = {}
    # 遍历所有注解项
    for arg_name, annotation in func.__annotations__.items():
        origin_type = get_origin(annotation)
        # 判断是否为联合类型
        if origin_type is Union or origin_type is types.UnionType:
            # 提取联合类型包含的所有子类型,转为列表存储
            parsed_result[arg_name] = list(get_args(annotation))
        else:
            # 非联合类型直接存储原始注解
            parsed_result[arg_name] = annotation
    return parsed_result

使用示例

# 测试函数
async def func(arg1: str, arg2: int, arg3: Union[str, int], arg4: bool | None):
    ...

print(parse_annotations(func))

运行输出结果为:

{'arg1': <class 'str'>, 'arg2': <class 'int'>, 'arg3': [<class 'str'>, <class 'int'>], 'arg4': [<class 'bool'>, <class 'NoneType'>]}

注意事项

  • Python 3.8以下版本没有get_origin和get_args,可以直接访问注解的私有属性annotation.__origin__获取原始类型、annotation.__args__获取子类型,但兼容性不如官方工具函数,建议优先升级Python版本。
  • Optional[T]本质是Union[T, None],也可以被正常解析,返回的列表会自动包含NoneType类型。

内容的提问来源于stack exchange,提问作者Trevor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 16:27:02