python
config_error
ai_generated
true
pydantic_core._pydantic_core.ValidationError: 1 个验证错误,实例已冻结 [type=frozen_instance]
pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings api_key Instance is frozen [type=frozen_instance, input_value='new-key', input_type=str]
ID: python/pydantic-configerror-frozen-field-mutation
80%修复率
89%置信度
0证据数
2024-09-08首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 2.x | active | — | — | — |
根因分析
BaseSettings/BaseModel 声明了 model_config = ConfigDict(frozen=True),代码在构造之后尝试给字段赋新值。
English
A BaseSettings/BaseModel was declared with model_config = ConfigDict(frozen=True), and code attempted to assign a new value to a field after construction.
解决方案
-
95% 成功率
new_settings = settings.model_copy(update={'api_key': 'new-key'}) -
90% 成功率
class Settings(BaseSettings): model_config = ConfigDict(frozen=False) api_key: str
无效尝试
常见但无效的做法:
-
55% 失败
Bypassing Pydantic's __setattr__ works at runtime but leaves the model's internal __pydantic_fields_set__ inconsistent and can break serialization.
-
90% 失败
frozen models also block __delattr__, raising TypeError: cannot delete field.