python
runtime_error
ai_generated
true
pydantic_core._pydantic_core.ValidationError:1 个验证错误(Config) __root__ 实例已冻结 [type=frozen_instance, input_value=Config(x=1), input_type=Config]
pydantic_core._pydantic_core.ValidationError: 1 validation error for Config __root__ Instance is frozen [type=frozen_instance, input_value=Config(x=1), input_type=Config]
ID: python/pydantic-model-frozen-mutation
80%修复率
85%置信度
0证据数
2024-06-18首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
模型声明为 model_config = ConfigDict(frozen=True),但构造后代码尝试修改其属性。
English
The model was declared with model_config = ConfigDict(frozen=True) and code attempted to mutate an attribute after construction.
解决方案
-
95% 成功率
c2 = c.model_copy(update={'x': 2}) assert c2.x == 2 and c.x == 1 -
90% 成功率
from pydantic import BaseModel, ConfigDict class Config(BaseModel): model_config = ConfigDict(frozen=False) x: int
无效尝试
常见但无效的做法:
-
70% 失败
There is no override; frozen is enforced via pydantic-core in Rust.
-
60% 失败
Bypasses validation and hash consistency, breaking dict/set usage of the model.
-
45% 失败
model_config is class-level; mutating it affects all instances and is not thread-safe.