Pydantic严格模式无法生效,如何强制触发验证错误?
Pydantic严格模式未触发验证错误的解决方法
按照Pydantic官方文档说明,以下两段启用严格模式的代码本应触发验证错误(传入字符串类型id但字段定义为int),但实际运行时字符串被直接强制转换为int类型,未触发预期错误。测试环境为Jupyter Notebook,不排除.ipynb文件对功能表现有影响。
测试代码
代码1(字段级严格模式)
from pydantic import BaseModel, ValidationError, Field class Student(BaseModel): id: int = Field(strict=True) s = Student(id="1")
代码2(模型级严格模式)
from pydantic import BaseModel, ValidationError, ConfigDict, Field class Student(BaseModel): model_config = ConfigDict(strict=True) id: int s = Student(id="1")
解决方法
- 检查Pydantic版本:严格模式是Pydantic v2新增的核心特性,v1版本中
strict参数的行为与v2文档描述完全不符。如果你的环境是v1,升级到v2即可解决问题。 - 清理Jupyter环境:在Notebook中测试时,重启内核后重新运行代码,避免之前的配置或变量残留干扰结果。
- 显式捕获验证错误:确保用
try-except块捕获ValidationError,才能看到预期的错误信息,示例代码如下:
from pydantic import BaseModel, ValidationError, ConfigDict class Student(BaseModel): model_config = ConfigDict(strict=True) id: int try: s = Student(id="1") except ValidationError as e: print(e)
运行后会输出预期的验证错误:
1 validation error for Student id Input should be a valid integer, got a string [type=int_type, input_value='1', input_type=str] For further information visit https://errors.pydantic.dev/2.5/v/int_type
内容的提问来源于stack exchange,提问作者jbuddy_13
相关产品推荐
相关产品推荐

