python config_error ai_generated true

pydantic.errors.PydanticUserError: Field 'tags' requires a default value or default_factory; mutable defaults are not allowed in Pydantic v2

ID: python/pydantic-nested-dict-default-mutable

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
2.x active

Root Cause

A mutable default (list, dict, set) was provided directly to a field, which Pydantic v2 rejects to avoid shared-state bugs.

generic

中文

字段直接使用了可变默认值(list、dict、set),Pydantic v2 为避免共享状态 bug 而拒绝此写法。

Workarounds

  1. 98% success
    from pydantic import BaseModel, Field
    class M(BaseModel):
        tags: list[str] = Field(default_factory=list)
  2. 90% success
    class M(BaseModel):
        tags: list[str] = []  # Pydantic copies per-instance

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Same mutable default problem; Pydantic raises at class definition.

  2. 50% fail

    Callers must handle None everywhere; downstream iteration crashes.

  3. 55% fail

    Bypasses Pydantic field metadata; model_dump and JSON schema lose the default.