Python TypedDict和Pydantic
本文最后更新于 2026年7月22日
TypedDict
TypedDict是Python里给字典添加类型提示的一种方式,从Python3.8开始引入。简单说,它能让你明确指定一个字典应该包含哪些键,以及每个键对应的值应该是什么类型,但是只是类型提示,运行时无强制检查,而且默认所有字段都是必须的。
from typing import TypedDict
class Student(TypedDict):
name: str
age: int
grade: float
if __name__ == '__main__':
s1 = Student(name='xiaomi', age=12, grade=120)
print(s1)
print(type(s1))
s2 = Student(name=12, age='xiaomi')
print(s2){'name': 'xiaomi', 'age': 12, 'grade': 120}
<class 'dict'>
{'name': 12, 'age': 'xiaomi'}运行时无强制检查,只能通过mypy等工具检查问题
pip install mypy(.venv) PS D:\python-lang-test\test1> mypy .\typed.py
typed.py:13: error: Missing key "grade" for TypedDict "Student" [typeddict-item]
Found 1 error in 1 file (checked 1 source file)Pydantic
Pydantic是一个第三方的,基于Python类型注解(Type Hints)的数据验证与模型构建库,与TypedDict相比,pydantic能自动完成类型检查、数据转换和格式验证,确保进入程序的数据是干净、合规的。
使用Pydantic,首先要安装
pip install pydantic例:使用pydantic,要继承BaseModel
from pydantic import BaseModel, ValidationError
class Cat(BaseModel):
age: int
name: str
if __name__ == '__main__':
try:
cat = Cat(age=12)
print(cat)
except ValidationError as e:
print(e)
1 validation error for Cat
name
Field required [type=missing, input_value={'age': 12}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.13/v/missing例:与typing.Annotated配合,校验字段格式:
from typing import Annotated
from pydantic import BaseModel, ValidationError, Field
class Cat(BaseModel):
age: Annotated[int, Field(ge=0, le=150, description='年龄,0到150岁')]
name: str
if __name__ == '__main__':
try:
cat = Cat(age=-12)
print(cat)
except ValidationError as e:
print(e)2 validation errors for Cat
age
Input should be greater than or equal to 0 [type=greater_than_equal, input_value=-12, input_type=int]
For further information visit https://errors.pydantic.dev/2.13/v/greater_than_equal
name
Field required [type=missing, input_value={'age': -12}, input_type=dict]
For further information visit https://errors.pydantic.dev/2.13/v/missing例:自定义校验规则
from pydantic import BaseModel, ValidationError, Field, field_validator
class Cat(BaseModel):
age: int = Field(description="产品名称")
name: str
@field_validator("age")
def validate_age(cls, value):
if value < 0 or value > 150:
raise ValueError('年龄,0到150岁')
return value
if __name__ == '__main__':
try:
cat = Cat(age=-12, name='qiangqiang')
print(cat)
except ValidationError as e:
print(e)
1 validation error for Cat
age
Value error, 年龄,0到150岁 [type=value_error, input_value=-12, input_type=int]
For further information visit https://errors.pydantic.dev/2.13/v/value_error对比
| 对比项 | TypedDict |
BaseModel |
|---|---|---|
| 来源 | 标准库 | pydantic |
| 定位 | 类型提示,轻量字典 | 强类型数据类型,含验证逻辑 |
| 运行时检查 | 无运行时校验 | 自动校验字段类型,默认值 |
| 继承自 | dict |
BaseModel |
| 性能 | 快 | 稍慢,需要解析和验证 |
| 序列化/反序列化 | 手动处理 | 自动,.dict() .json() |
| 用途场景 | 简单的数据结构定义 | 需要验证,解析和约束的模型 |
"如果文章对您有帮助,可以请作者喝杯咖啡吗?"
微信支付
支付宝
Python TypedDict和Pydantic
https://blog.liuzijian.com/post/python/2026/04/12/python-typed_dict-pydantic/