python config_error ai_generated true

pydantic.errors.ConfigError: 字段验证器必须返回值

pydantic.errors.ConfigError: A field validator must return the value

ID: python/pydantic-field-validator-missing-return

其他格式: JSON · Markdown 中文 · English
80%修复率
82%置信度
0证据数
2024-02-20首次发现

版本兼容性

版本状态引入弃用备注
2.x active

根因分析

在 Pydantic v2 中,@field_validator 装饰的函数必须返回值;如果返回 None 或不返回,Pydantic 会因验证链断裂而抛出 ConfigError。

English

A @field_validator decorated function in Pydantic v2 must return the value; if it returns None or doesn't return, Pydantic raises ConfigError because the validation chain breaks.

generic

解决方案

  1. 95% 成功率
    Ensure validator returns the value: @field_validator('field') def validate_field(cls, v): return v
  2. 90% 成功率
    Use mode='before' and still return the value, e.g., return v.strip()

无效尝试

常见但无效的做法:

  1. 90% 失败

    Pydantic expects a value to continue processing; None causes ConfigError.

  2. 60% 失败

    Raising exceptions is fine, but if no exception and no return, it fails.