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

如何引用其他类实例变量的类型提示?以OpenAI Batch类为例

解决方法

方法1:通过__annotations__直接提取类型

直接从Batch类的__annotations__字典中获取status对应的类型定义,无需复制Literal表达式:

from typing import TypedDict
from openai.types import Batch

class FileStatus(TypedDict):
    status: Batch.__annotations__['status']
    # 可添加其他自定义字段

方法2:用get_type_hints解析真实类型

如果__annotations__中存在延迟解析的字符串类型标注,使用get_type_hints能拿到解析后的真实类型:

from typing import TypedDict, get_type_hints
from openai.types import Batch

# 先获取Batch类所有字段的解析后类型
batch_type_hints = get_type_hints(Batch)

class FileStatus(TypedDict):
    status: batch_type_hints['status']
    # 可添加其他自定义字段

方法3:先定义类型别名再复用

如果需要多次使用该类型,可提前定义别名:

from typing import TypedDict
from openai.types import Batch

# 提取status类型作为别名
BatchStatus = Batch.__annotations__['status']

class FileStatus(TypedDict):
    status: BatchStatus
    # 可添加其他自定义字段

报错原因说明

直接引用Batch.status会报错,是因为Batch.status是类的实例属性,并非类型注解本身,Pylance无法将其识别为类型提示的合法来源。而__annotations__字典存储了类字段的原始类型注解定义,get_type_hints则会处理注解的解析逻辑,确保拿到正确的类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 08:30:53