20260617:目前有914 页
This commit is contained in:
48
concepts/typeadapter.md
Normal file
48
concepts/typeadapter.md
Normal file
@@ -0,0 +1,48 @@
|
||||
---
|
||||
title: "TypeAdapter"
|
||||
created: 2026-06-10
|
||||
updated: 2026-06-10
|
||||
type: concept
|
||||
tags: [pydantic, validation, type-safety]
|
||||
sources: [raw/articles/pydantic-three-piece-suite-2026.md]
|
||||
---
|
||||
|
||||
# TypeAdapter
|
||||
|
||||
> [[pydantic-core|pydantic-core]] 提供的灵活校验接口——同一份数据,不同严格度。无需写两套模型定义。
|
||||
|
||||
## 核心场景
|
||||
|
||||
API 入参需要严格校验(字段不能多、类型不能松),但同一个模型在 Agent 内部传递时想宽松一点(Agent 中间步骤输出不稳定,太严阻碍流程)。
|
||||
|
||||
## 使用方式
|
||||
|
||||
```python
|
||||
from pydantic import BaseModel, TypeAdapter
|
||||
|
||||
class UserProfile(BaseModel):
|
||||
name: str
|
||||
age: int
|
||||
email: str | None = None
|
||||
model_config = {"extra": "forbid"}
|
||||
|
||||
# 严格模式——API 入口
|
||||
api_validator = TypeAdapter(UserProfile)
|
||||
|
||||
# 宽松模式——Agent 内部传递
|
||||
internal_validator = TypeAdapter(Any)
|
||||
|
||||
# 同一份数据,不同入口
|
||||
profile = api_validator.validate_python(raw_data) # 硬校验
|
||||
flexible = internal_validator.validate_python(raw_data) # 宽松
|
||||
```
|
||||
|
||||
## 实用进阶
|
||||
|
||||
真正实用的不是切换类型——是 `strict` 参数和 `frozen` 配置在同一个模型定义上的不同用法。例如 API 入口用 `strict=True`,内部模块用 `strict=False`。
|
||||
|
||||
## 参考
|
||||
|
||||
- [[pydantic-core|pydantic-core]]
|
||||
- [[pydantic|Pydantic]]
|
||||
- [[pydantic-three-piece-suite|Pydantic 三件套]]
|
||||
Reference in New Issue
Block a user