python config_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
89%Confidence
0Evidence
2024-09-08First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active — — —

Root Cause

A BaseSettings/BaseModel was declared with model_config = ConfigDict(frozen=True), and code attempted to assign a new value to a field after construction.

generic

中文

BaseSettings/BaseModel 声明了 model_config = ConfigDict(frozen=True),代码在构造之后尝试给字段赋新值。

Workarounds

  1. 95% success
    new_settings = settings.model_copy(update={'api_key': 'new-key'})
  2. 90% success
    class Settings(BaseSettings):
        model_config = ConfigDict(frozen=False)
        api_key: str

Dead Ends

Common approaches that don't work:

  1. 55% fail

    Bypassing Pydantic's __setattr__ works at runtime but leaves the model's internal __pydantic_fields_set__ inconsistent and can break serialization.

  2. 90% fail

    frozen models also block __delattr__, raising TypeError: cannot delete field.