python config_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 validation error for User name Instance is frozen [type=frozen_instance, input_value='Bob', input_type=str]

ID: python/pydantic-immutable-frozen-assignment

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —

Root Cause

The model was declared with model_config = ConfigDict(frozen=True), so any attribute assignment after construction raises a frozen_instance error.

generic

中文

模型声明了 model_config = ConfigDict(frozen=True),因此构造后任何属性赋值都会引发 frozen_instance 错误。

Workarounds

  1. 95% success
    new_user = user.model_copy(update={'name': 'Bob'})
  2. 90% success
    class User(BaseModel):
        model_config = ConfigDict(frozen=False)  # default
        name: str

Dead Ends

Common approaches that don't work:

  1. 75% fail

    Bypasses Pydantic's checks and produces an inconsistent model that violates __hash__ and equality guarantees.

  2. 85% fail

    Corrupts the model's internal fields storage and can raise KeyError or produce an invalid state.