20260617:目前有914 页

This commit is contained in:
2026-06-17 15:02:40 +08:00
parent e96b955fda
commit 91fac5b6fc
423 changed files with 20687 additions and 34 deletions

53
concepts/pydantic-core.md Normal file
View File

@@ -0,0 +1,53 @@
---
title: "pydantic-core"
created: 2026-06-10
updated: 2026-06-10
type: concept
tags: [pydantic, rust, validation, performance]
sources: [raw/articles/pydantic-three-piece-suite-2026.md]
---
# pydantic-core
> [[pydantic|Pydantic]] 生态的物理引擎——Rust 编写的校验核心,通过 PyO3 绑定到 Python完全脱离 GIL。
## 校验流程
当调用 `model_validate(data)` 时:
1. Python 层将模型定义转为 **CoreSchema JSON**(一份"校验指令"
2. CoreSchema JSON 通过 PyO3 传给 Rust 层
3. Rust 层按 schema 逐字段校验、类型转换、处理嵌套
4. 返回校验通过的类型化 Python 对象,或 `ValidationError`
**关键**:步骤 2-4 全部在 Rust 侧完成,不走 GIL。
## 性能
| 场景 | 纯 Python | pydantic-core | 倍数 |
|------|----------|--------------|------|
| 简单模型 1000 次 | ~12ms | ~1.5ms | 8× |
| 嵌套 3 层 10000 次 | ~450ms | ~35ms | 13× |
| JSON 大文件反序列化 | ~800ms | ~48ms | 17× |
| 内存峰值 | 基线 | -35% | — |
## 对 AI 开发者的关键意义
- `asyncio.gather()` 并发 20 个 LLM API 调用时,每个回复的 JSON 解析在不同线程并行跑 Rust 校验,互不阻塞
- 深层嵌套模型收益最大——每层嵌套原来都是 Python 层的递归开销
## 三配置升级
```python
model_config = {
"strict": True, # 类型不匹配直接炸,不静默转换
"extra": "forbid", # 多字段立刻报错
"frozen": True, # 创建后不可修改
}
```
## 参考
- [[pydantic|Pydantic 生态]]
- [[typeadapter|TypeAdapter]]
- [[pydantic-three-piece-suite|Pydantic 三件套]]