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

如何在Python中访问Annotated类型提示的属性?

解决Annotated类型提示中提取元数据实例的问题

要获取Annotated类型提示里的B实例,关键是利用Python typing模块的公共API解析Annotated的结构,具体步骤如下:

  1. 获取类的注解
    可以使用inspect.get_annotations,或者直接访问类的__annotations__属性(当注解不是字符串形式定义时,后者更直接)。

  2. 解析Annotated结构
    用typing.get_origin判断注解是否为Annotated类型,再通过typing.get_args提取其中的原始类型和元数据项。

完整示例代码:

from typing import Annotated, get_origin, get_args
from dataclasses import dataclass
import inspect

@dataclass
class B:
    x: str

@dataclass
class A:
    y: Annotated[str, B(x="foo")]

# 获取A类的所有注解
annotations = inspect.get_annotations(A, eval_str=True)
# 取出y属性的注解
y_anno = annotations["y"]

# 检查是否是Annotated类型
if get_origin(y_anno) is Annotated:
    # get_args返回元组:(原始类型, 元数据1, 元数据2...)
    _, b_instance = get_args(y_anno)
    # 访问B实例的属性
    print(b_instance.x)  # 输出: foo

如果你的注解是通过字符串形式定义的(比如y: "Annotated[str, B(x='foo')]"),eval_str=True参数会自动求值字符串,确保你能拿到实际的Annotated对象和B实例。

也可以直接从类的__annotations__属性获取注解,效果一致:

y_anno = A.__annotations__["y"]
if get_origin(y_anno) is Annotated:
    _, b_instance = get_args(y_anno)
    print(b_instance.x)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:08:11