認識 Pydantic
Pydantic 是 Python 最廣泛使用的資料驗證(data validation)函式庫:你用型別提示(type hints)描述資料長什麼樣子,Pydantic 就在執行期幫你檢查、轉換並序列化資料。外部進來的 JSON、API 請求、設定檔、LLM 輸出,只要先經過 Pydantic 模型,程式後段就能放心使用「型別正確」的物件。
FastAPI、LangChain、OpenAI/Anthropic Python SDK、Pydantic AI 等熱門專案都以 Pydantic 為核心;Pydantic V2 的驗證核心 pydantic-core 以 Rust 撰寫,速度比 V1 快 5~50 倍。本站以 Pydantic V2 為準。
核心概念
Pydantic 的功能很多,但日常開發九成以上只用到下面這些。先把這幾項學熟,就能應付大部分專案:
-
一個核心類別:
BaseModel
繼承
BaseModel、用型別提示宣告欄位,就是一個會自動驗證的資料模型。 -
一個欄位工具:
Field
設定預設值、數值範圍、字串長度、別名(alias)與說明文字。
-
兩種驗證器
@field_validator驗證單一欄位,@model_validator檢查多個欄位之間的關係。 -
四個進出方法
model_validate/model_validate_json把資料讀進來,model_dump/model_dump_json把資料輸出去。
再加上兩個「實戰必備」:讀懂 ValidationError 的錯誤訊息,以及用 pydantic-settings 管理環境變數。學完這六項,再去碰 FastAPI 或 LLM 結構化輸出,會發現它們只是同一套觀念的延伸。
30 秒看懂 Pydantic 在做什麼
from pydantic import BaseModel, ValidationError
class User(BaseModel):
id: int
name: str
is_active: bool = True
# 字串 "42" 會被轉成整數 42,"yes" 會被轉成 True
user = User.model_validate({"id": "42", "name": "Alice", "is_active": "yes"})
print(user) # id=42 name='Alice' is_active=True
try:
User.model_validate({"id": "abc", "name": "Bob"})
except ValidationError as e:
print(e.error_count(), "個錯誤") # 1 個錯誤:id 不是合法整數
這段程式展示了 Pydantic 的三個核心行為:依型別驗證、合理的型別轉換(coercion)、清楚的錯誤回報。
學習路線
| 階段 | 分類 | 你會學到 |
|---|---|---|
| 1 | 入門基礎 | 為什麼需要 Pydantic、安裝、BaseModel、型別與 Field |
| 2 | 驗證與序列化 | 驗證器、錯誤處理、model_dump、巢狀模型 |
| 3 | 進階應用 | model_config、pydantic-settings、TypeAdapter、JSON Schema、V1 遷移 |
| 4 | 生態系實戰 | FastAPI 請求/回應模型、LLM 結構化輸出與 Pydantic AI |
| — | 推薦影音 | 官方演講與優質 YouTube 教學整理 |
常見問題
Pydantic 跟 Python 的型別提示有什麼不同?
Python 的型別提示只是「註解」,執行時不會檢查;Pydantic 則在建立物件時真的依型別驗證與轉換資料。型別檢查器(mypy、Pyright)在開發階段找錯,Pydantic 在執行階段擋住外部的壞資料,兩者互補。
Pydantic 跟 dataclasses 該選哪一個?
資料來自外部(API、檔案、使用者輸入、LLM)時選 Pydantic,因為需要驗證與轉換;資料完全由自己的程式產生、只是想少寫 __init__ 時,標準函式庫的 dataclasses 就夠了。Pydantic 也提供 pydantic.dataclasses,可以在保留 dataclass 寫法的同時加上驗證。
Pydantic V1 的教學還能看嗎?
觀念可以參考,但 API 名稱已經改了:.dict() 變成 .model_dump()、@validator 變成 @field_validator、class Config 變成 model_config。新專案請直接用 V2,舊專案可參考 V1 遷移到 V2。
Pydantic 要錢嗎?
Pydantic 函式庫是 MIT 授權的開源軟體,免費使用。Pydantic 公司另有商業的可觀測性(observability)服務 Logfire,與函式庫本身無關,不用也能完整使用 Pydantic。
先看這支影片
Corey Schafer:Pydantic 完整資料驗證課程
簡述:涵蓋建立模型、欄位驗證、自訂驗證器、型別轉換、巢狀模型與模型設定,節奏清楚,適合當作本站的影音版總覽。更多影片請見 推薦影音。
官方資源
- Pydantic 官方文件:最權威的 API 說明與概念章節。
- Pydantic GitHub:原始碼、Issue 與版本紀錄。
- Pydantic 官方 YouTube 頻道:Pydantic 公司發布的演講、Logfire 與 Pydantic AI 教學。
沒有官方認證課程
Pydantic 目前沒有官方的認證(Certification)或證照課程。想系統學習,建議依本站學習路線搭配官方文件,再用 FastAPI 或 LLM 小專案實際練習。