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

如何从typing.Annotated中移除注解,提取纯净类型提示?

提取Annotated类型中的原始类型结构

问题核心

你的场景需要递归剥离所有嵌套的Annotated包装——因为Point3D本身也是Annotated类型,仅取外层get_args只能得到带注解残留的中间类型,正则替换则因类型字符串的灵活性容易失效。

解决方案:递归解析类型结构

通过typing模块的get_origin和get_args工具,写一个递归函数逐层剥离Annotated,同时处理泛型类型的嵌套参数:

from typing import Annotated, get_origin, get_args

# 修正原代码笔误:list的类型参数应为单个元素类型,而非多个
Point3D = Annotated[tuple[float, float, float], "A 3D Point"]
Points = Annotated[list[Point3D], "A collection of points"]

def strip_annotated(type_obj):
    # 循环剥离外层Annotated包装
    while get_origin(type_obj) is Annotated:
        type_obj = get_args(type_obj)[0]
    # 递归处理泛型类型的参数(比如list、tuple的内部元素类型)
    origin = get_origin(type_obj)
    if origin is not None:
        cleaned_args = tuple(strip_annotated(arg) for arg in get_args(type_obj))
        return origin[cleaned_args]
    return type_obj

# 测试提取
raw_type = strip_annotated(Points)
print(raw_type)  # 输出:list[tuple[float, float, float]]

关键逻辑说明

  1. 外层剥离:用get_origin判断当前类型是否为Annotated,如果是则取第一个参数(原始类型部分),循环直到拿到非Annotated类型
  2. 泛型处理:针对list、tuple这类泛型类型,递归清理它们的每个参数,再重新构造纯净的泛型类型结构
  3. 可靠性:完全基于Python类型系统的原生工具解析,比正则替换更适配复杂嵌套、自定义泛型等场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 14:04:59