如何为遍历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
相关产品推荐
相关产品推荐

