OpenAI Python 类型定义了一个
Batch
类,带有 status
字段:
class Batch(BaseModel):
id: str
# ...
status: Literal[
"validating", "failed", "in_progress", "finalizing", "completed", "expired", "cancelling", "cancelled"
]
"""The current status of the batch."""
我想在我自己的班级中重新使用
Literal[...]
字段中的 status
类型提示。这是一个尝试:
from typing import Optional, TypedDict
import openai
class FileStatus(TypedDict):
filename: str
sha256: str
file_id: Optional[str]
batch_id: Optional[str]
batch_status: Optional[openai.types.Batch.status]
# ~~~~~~
# Variable not allowed in type expression Pylance(reportInvalidTypeForm)
我应该使用什么作为
batch_status
的类型提示?如果可能的话,我希望避免从 OpenAI API 复制/粘贴 Literal[...]
表达式。
from typing import Literal, Optional, TypedDict, get_type_hints
class Batch:
id: str
status: Literal[
"validating", "failed", "in_progress", "finalizing", "completed", "expired", "cancelling", "cancelled"
]
type_hints = get_type_hints(Batch)
status_type = type_hints['status']
class FileStatus(TypedDict):
filename: str
sha256: str
file_id: Optional[str]
batch_id: Optional[str]
batch_status: Optional[status_type]
您可以使用输入中的 get_type_hints 从类中获取属性类型。