python runtime_error ai_generated true

pydantic_core._pydantic_core.ValidationError: 1 个验证错误 (Config) field_name 实例已冻结 [type=frozen_instance, input_value='new', input_type=str]

pydantic_core._pydantic_core.ValidationError: 1 validation error for Config field_name Instance is frozen [type=frozen_instance, input_value='new', input_type=str]

ID: python/pydantic-model-frozen-assignment

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

版本兼容性

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

根因分析

尝试修改设置了 `model_config = ConfigDict(frozen=True)` 的模型属性。

English

Attempting to mutate an attribute on a model with `model_config = ConfigDict(frozen=True)`.

generic

解决方案

  1. 95% 成功率
    Use `model_copy(update={'field_name': 'new'})` to produce a new instance.
  2. 85% 成功率
    Remove `frozen=True` if mutability is required, or use `object.__setattr__(obj, 'field_name', 'new')` as a last resort.

无效尝试

常见但无效的做法:

  1. 90% 失败

    Using `setattr` bypasses type checkers but still raises at runtime.

  2. 70% 失败

    Mutating `__dict__` directly works but breaks hashing and Pydantic invariants.