Pydantic 修改输入

Pydantic mangling input

在下面的示例中,我无法理解为什么 pydantic 会破坏类型输入。

from pydantic import BaseModel
from typing import Union, List


class Foo(BaseModel):
    bar: Union[str, dict, List[dict]]

f = Foo(bar=[{'foo': 'bar', 'stuff': 'things'}])
assert f.bar == {'foo': 'stuff'}

为什么类型从列表变为字典并进一步将键分解为键值对?不知道这是 pydantic 特有的还是只是打字问题。

作为后续,我可以做些什么来解决这个问题,这样类型就不会被破坏。

答案来自 asking in the repo

基本上,如果您包含 smart union 配置值,则此问题已在最新版本的 pydantic 中修复。

from pydantic import BaseModel
from typing import Union, List


class Foo(BaseModel, smart_union=True):
    bar: Union[str, dict, List[dict]]

f = Foo(bar=[{'foo': 'bar', 'stuff': 'things'}])
assert f.bar == [{'foo': 'bar', 'stuff': 'things'}]