python type_error ai_generated true

TypeError: FieldInfo.__init__() 收到意外的关键字参数 'default_factory'

TypeError: FieldInfo.__init__() got an unexpected keyword argument 'default_factory' when used with a positional default in Field(...)

ID: python/pydantic-field-info-missing-default

其他格式: JSON · Markdown 中文 · English
80%修复率
84%置信度
0证据数
2024-05-08首次发现

版本兼容性

版本状态引入弃用备注
2.x active — — —

根因分析

Field() 同时传入了位置默认值和 default_factory,存在歧义,被 Pydantic v2 更严格的 FieldInfo 签名拒绝。

English

Field() is called with both a positional default value and default_factory, which is ambiguous and rejected by Pydantic v2's stricter FieldInfo signature.

generic

解决方案

  1. 98% 成功率
    Use only default_factory:
    
    class M(BaseModel):
        items: list[int] = Field(default_factory=list)
  2. 85% 成功率
    Or use only a positional default:
    
    class M(BaseModel):
        items: list[int] = []  # careful: mutable default is copied by pydantic

无效尝试

常见但无效的做法:

  1. 90% 失败

    Raises TypeError at import time before any model is instantiated.

  2. 50% 失败

    Breaks immutability guarantees and validation order; often still yields None when callers inspect the field.