python
config_error
ai_generated
true
pydantic_core._pydantic_core.ValidationError: 1 个验证错误,实例已冻结,无法修改字段 name [类型=frozen_instance]
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
80%修复率
90%置信度
0证据数
2024-04-11首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
模型声明了 model_config = ConfigDict(frozen=True),因此构造后任何属性赋值都会引发 frozen_instance 错误。
English
The model was declared with model_config = ConfigDict(frozen=True), so any attribute assignment after construction raises a frozen_instance error.
解决方案
-
95% 成功率
new_user = user.model_copy(update={'name': 'Bob'}) -
90% 成功率
class User(BaseModel): model_config = ConfigDict(frozen=False) # default name: str
无效尝试
常见但无效的做法:
-
75% 失败
Bypasses Pydantic's checks and produces an inconsistent model that violates __hash__ and equality guarantees.
-
85% 失败
Corrupts the model's internal fields storage and can raise KeyError or produce an invalid state.