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

如何为遍历Union与Literal的Python函数添加类型注解?

为遍历Union与Literal的函数添加类型注解

可行实现方案

利用Python 3.10+引入的UnionType,结合TypeVar覆盖常见字面量类型,即可完成正确的类型注解,代码如下:

from typing import get_origin, get_args, Literal, Union, Iterable, TypeVar
from types import UnionType

# 定义TypeVar覆盖常见字面量类型
LiteralVal = TypeVar('LiteralVal', str, int, float, bool, type(None))
# 输入类型:包含UnionType和Literal泛型别名
InputType = Union[UnionType, type[Literal[LiteralVal]]]

def traverse_union(union_type: InputType) -> Iterable[type | LiteralVal]:
    origin = get_origin(union_type)
    
    if origin in {Union, Literal}:
        for argument in get_args(union_type):
            yield from traverse_union(argument)
        return
    
    yield union_type

print(list(traverse_union(int | float | Literal["Hello, world!"]))) 
# 输出: [<class 'int'>, <class 'str'>, 'Hello, world!']

关键说明

  • UnionType对应int | float这类语法生成的联合类型,而Union[int, float]的类型起源是Union
  • 用type[Literal[LiteralVal]]标注Literal的泛型别名类型,若需支持枚举等其他字面量类型,直接将其添加到TypeVar的约束列表即可
  • 返回类型Iterable[type | LiteralVal]明确了函数会产出常规类型或字面量值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 08:48:25