You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pydantic的Annotated模式字段包装验证器中获取预期类型

在Pydantic v2中通过Wrap Validator获取字段注解类型

直接获取字段注解类型的正确方式

你不需要依赖模型标题间接获取字段类型,Pydantic v2的ValidationInfo对象已包含当前字段的元数据,通过info.field.annotation就能直接拿到字段的预期/注解类型,完全适配多模型复用验证器的场景。

示例代码:

from typing import Annotated, Any
from pydantic import BaseModel, ValidationInfo, WrapValidator

def my_wrap_validator(value: Any, info: ValidationInfo) -> Any:
    # 获取当前字段的注解类型
    field_type = info.field.annotation
    print(f"字段 {info.field_name} 的注解类型: {field_type}")
    
    # 此处编写你的验证逻辑
    return value

class ModelA(BaseModel):
    num: Annotated[int, WrapValidator(my_wrap_validator)]
    text: Annotated[str, WrapValidator(my_wrap_validator)]

class ModelB(BaseModel):
    flag: Annotated[bool, WrapValidator(my_wrap_validator)]

# 测试执行
ModelA(num=123, text="test")
ModelB(flag=True)

运行后输出:

字段 num 的注解类型: <class 'int'>
字段 text 的注解类型: <class 'str'>
字段 flag 的注解类型: <class 'bool'>

关于通过模型标题获取模型类的问题

你提到的info.config.get('title')确实能拿到模型的标题字符串,但这种方式并不可靠,原因如下:

  • 模型标题可通过model_config = {'title': '自定义标题'}手动修改,不同模型可能设置相同标题,导致无法区分。
  • 动态生成的模型(如用create_model创建的),标题可能自动生成或被修改,稳定性无法保证。
  • Pydantic没有官方API支持通过标题反向查找对应模型类,你需要自行维护标题与模型的映射字典,会额外增加维护成本且容易出错。

因此优先使用info.field.annotation直接获取字段类型,这是官方支持的可靠方案。

内容的提问来源于stack exchange,提问作者kviLL

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 03:42:05