python runtime_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 validation error for Model Instance is frozen [type=frozen_instance, input_value=..., input_type=...]

ID: python/pydantic-immutability-error

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —

Root Cause

Model was defined with model_config = ConfigDict(frozen=True), so any attempt to mutate attributes after creation raises frozen_instance.

generic

中文

模型被定义为 model_config = ConfigDict(frozen=True),因此创建后任何修改属性的尝试都会引发 frozen_instance。

Workarounds

  1. 97% success
    new = old.model_copy(update={'name': 'new'})
  2. 99% success
    class M(BaseModel):
        model_config = ConfigDict(frozen=False)

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Pydantic v2 intercepts __setattr__ at the C level; bypassing breaks hashing invariants.

  2. 40% fail

    Works but loses identity and any registered validators may re-run unexpectedly.