Search code examples
pythontypingpydantic

Pydantic mangling input


In the following example, I can't understand why pydantic is mangling the type input.

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'}

Why is the type changing from a list to a dict and further mangling the keys into a key value pair? Don't know if this is pydantic specific or just typing issues.

And as a followup, what can I do to fix this so that the types aren't mangled.


Solution

  • Answer came from asking in the repo.

    Basically this was fixed in the most recent version of pydantic if you include a smart union config value.

    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'}]