Pydantic简单模型未按预期校验,如何阻止自动类型转换?
解决Pydantic 0.18.2自动类型转换问题
Pydantic 0.18.2默认开启类型自动转换,要禁用该行为,可通过以下两种方式实现严格类型校验:
1. 全局开启严格模式
在模型的Config类中设置strict=True,让所有字段都强制执行严格类型校验,类型不匹配时直接抛出ValidationError。
示例代码:
from pydantic import BaseModel, ValidationError class Person(BaseModel): name: str age: int is_student: bool class Config: strict = True # 测试类型不匹配场景 try: # age传入字符串、is_student传入整数,触发校验错误 p = Person(name="Alice", age="25", is_student=1) except ValidationError as e: print(e)
2. 单个字段开启严格模式
如果仅需部分字段禁用自动转换,可在字段定义时使用Field(strict=True)单独配置。
示例代码:
from pydantic import BaseModel, Field, ValidationError class Person(BaseModel): name: str = Field(strict=True) age: int = Field(strict=True) is_student: bool # 测试name传入整数的场景 try: p = Person(name=123, age="25", is_student=1) except ValidationError as e: print(e)
此示例中仅name和age字段会严格校验类型,is_student仍保留自动转换行为。
注意事项
strict参数在Pydantic 0.18.2中是生效的,但后续版本的配置逻辑有所调整,若后续升级版本需留意文档变化。- 严格模式下会增强校验规则,比如空白字符串、字符串形式的数字都会被判定为不符合类型要求。
内容的提问来源于stack exchange,提问作者BobbyF
相关产品推荐
相关产品推荐

