python runtime_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 validation error for Model 实例已冻结 [type=frozen_instance, input_value=..., input_type=...]

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

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

版本兼容性

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

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 80% 失败

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

  2. 40% 失败

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