Pydantic 动态字段:使用和不使用 `@computed_field` 的对比指南
在数据建模时,我们经常需要定义动态字段,基于模型中其他字段计算出结果。
Pydantic 提供了一个专门的装饰器 @computed_field
,用于声明这样的动态字段。但即使不使用 @computed_field
,也能通过普通的 Python 属性实现类似的效果。
本文将通过两种实现方式的对比,帮助你理解何时选择 @computed_field
,以及它的优势。
安装 Pydantic
确保已安装最新版本的 Pydantic:
pip install pydantic
不使用 @computed_field
的实现
我们可以通过普通的 Python @property
定义动态字段:
from pydantic import BaseModel, Field
class LLMUsageMetrics(BaseModel):
"""LLM request usage metrics."""
input_tokens: int = Field(0, description="Used input tokens by the request")
output_tokens: int = Field(0, description="Used output tokens by the request")
@property
def total_tokens(self) -> int:
"""Total tokens used by the request."""
return self.input_tokens + self.output_tokens