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
80%Fix Rate
89%Confidence
0Evidence
2024-02-08First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
98% success
from pydantic import BaseModel, Field class M(BaseModel): tags: list[str] = Field(default_factory=list) -
90% success
class M(BaseModel): tags: list[str] = [] # Pydantic copies per-instance
Dead Ends
Common approaches that don't work:
-
70% fail
Same mutable default problem; Pydantic raises at class definition.
-
50% fail
Callers must handle None everywhere; downstream iteration crashes.
-
55% fail
Bypasses Pydantic field metadata; model_dump and JSON schema lose the default.