python config_error ai_generated true

pydantic.errors.PydanticUserError: `model_config` cannot be used as a model field name. Use `model_config` for model configuration.

ID: python/pydantic-config-error-json-schema-extra

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-04-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —

Root Cause

A v2 model defines an attribute literally named `model_config` (often ported from v1 code where the field was user-defined), which Pydantic reserves for configuration.

generic

中文

v2 模型中定义了名为 `model_config` 的属性(通常从 v1 代码移植而来),而 Pydantic 保留该名称用于配置。

Workarounds

  1. 95% success
    Rename the field and add an alias: `class M(BaseModel):
        model_config = ConfigDict(populate_by_name=True)
        cfg: dict = Field(alias='model_config')`
  2. 90% success
    Use `Field(alias='model_config')` and read via `obj.cfg`; update all callers to use the new attribute name.

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Renaming only in the class but not in callers leaves `AttributeError` at runtime when code reads `obj.model_config`.

  2. 90% fail

    Adding `class Config` alongside `model_config` triggers a second PydanticUserError about mixing v1 and v2 config styles.