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

如何读取Python中Annotated对象的扩展注解?

如何访问Annotated类型中的额外注解内容

PEP 593 通过Annotated为Python类型注解添加了扩展能力,但该PEP及Annotated的官方文档并未明确说明如何读取其中存储的额外注解内容。当你通过get_type_hints(指定include_extras=True参数)获取到Annotated对象后,可以通过以下方式提取额外注解:

Annotated实例包含两个特殊属性用于访问内部内容:

  • __origin__:对应被包装的原始类型(比如示例中的int)
  • __args__:一个元组,第一个元素是原始类型,后续所有元素就是你添加的额外注解

完整示例代码

from typing import Annotated
from inspect import get_type_hints

class Foo:
    bar: Annotated[int, "save"] = 5

hints = get_type_hints(Foo, include_extras=True)
annotated_obj = hints["bar"]

# 获取原始类型
original_type = annotated_obj.__origin__
# 获取所有额外注解(跳过第一个原始类型元素)
extra_annotations = annotated_obj.__args__[1:]

print(original_type)  # 输出: <class 'int'>
print(extra_annotations)  # 输出: ('save',)
# 若需要转为列表格式
print(list(extra_annotations))  # 输出: ['save']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:05:19