`model_construct` 与 `validation_alias=AliasPath(...)` 和 `extra='allow'` 会将别名路径键保留在 `model_extra` 中
作者: beduldul创建于 2026年9月25日更新于 2026年9月25日
In BaseModel.model_construct, the code walks the model's fields and removes each field's alias from the values dict before what remains is treated as extras. The three branches are not equivalent. On the installed release, pydantic 2.13.5, in main.py:
- lines 344-345: the
field.aliasbranch —values.pop(field.alias). - line 357: the
strvalidation alias branch —values.pop(alias). - line 361: the
AliasPathbranch —value = alias.search_dict_for_path(values). - line 376:
_extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None.
On main as of a9a0e1d1, the same four points are at lines 361-362, 374, 378 and 393 respectively. What differs is the shape of the operation. The first two branches pop from values, so a key consumed through field.alias or through a str validation_alias is gone by the time _extra is assigned. The AliasPath branch calls
内容来源: pydantic/pydantic