python config_error ai_generated true

pydantic_core._pydantic_core.ValidationError:User 出现 2 个验证错误 foo 不允许额外输入 [type=extra_forbidden, input_value='bar', input_type=str]

pydantic_core._pydantic_core.ValidationError: 2 validation errors for User foo Extra inputs are not permitted [type=extra_forbidden, input_value='bar', input_type=str]

ID: python/pydantic-extra-forbidden

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

版本兼容性

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

根因分析

model_config 设置了 extra='forbid'。传入的字典包含模型未声明的键。

English

model_config has extra='forbid'. The incoming dict contains keys not declared on the model.

generic

解决方案

  1. 90% 成功率
    class User(BaseModel):
        model_config = ConfigDict(extra='forbid')
        foo: str | None = None
  2. 85% 成功率
    class User(BaseModel):
        model_config = ConfigDict(extra='allow')

无效尝试

常见但无效的做法:

  1. 55% 失败

    Silently drops fields users expect to be persisted, causing data loss bugs.

  2. 50% 失败

    Hides schema drift; clients keep sending wrong fields and you never notice.

  3. 70% 失败

    Pydantic v2 does not accept **kwargs in BaseModel subclasses; raises PydanticUserError.