python runtime_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
90%Confidence
0Evidence
2024-07-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 90% fail

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

  2. 70% fail

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