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

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 95% 成功率
    c2 = c.model_copy(update={'x': 2})
    assert c2.x == 2 and c.x == 1
  2. 90% 成功率
    from pydantic import BaseModel, ConfigDict
    class Config(BaseModel):
        model_config = ConfigDict(frozen=False)
        x: int

无效尝试

常见但无效的做法:

  1. 70% 失败

    There is no override; frozen is enforced via pydantic-core in Rust.

  2. 60% 失败

    Bypasses validation and hash consistency, breaking dict/set usage of the model.

  3. 45% 失败

    model_config is class-level; mutating it affects all instances and is not thread-safe.