python runtime_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-06-18First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active

Root Cause

The model was declared with model_config = ConfigDict(frozen=True) and code attempted to mutate an attribute after construction.

generic

中文

模型声明为 model_config = ConfigDict(frozen=True),但构造后代码尝试修改其属性。

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 70% fail

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

  2. 60% fail

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

  3. 45% fail

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