python config_error ai_generated true

pydantic.errors.ConfigError: 'extra' must be a string or dict

ID: python/pydantic-config-extra-forbid

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-03-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active

Root Cause

In Pydantic v2, the 'extra' config option only accepts specific string values ('allow', 'ignore', 'forbid') or a dict, not a boolean or arbitrary string.

generic

中文

在 Pydantic v2 中,'extra' 配置选项只接受特定字符串值('allow'、'ignore'、'forbid')或字典,不接受布尔值或任意字符串。

Workarounds

  1. 90% success
    Set extra='forbid' or 'allow' in model config: class Model(BaseModel): model_config = ConfigDict(extra='forbid')
  2. 85% success
    Use a dict to customize extra fields: model_config = ConfigDict(extra={'field': 'value'})

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Boolean values are not valid for 'extra' in v2; it requires string or dict, leading to ConfigError.

  2. 70% fail

    'extra' does not accept a list; it must be a string or dict, so this raises ConfigError.