Skip to content

Union Type with Submodels in Settings class raises a ValidationError #2936

@cbartz

Description

@cbartz

Checks

  • I added a descriptive title to this issue
  • I have searched (google, github) for similar issues and couldn't find anything
  • I have read and followed the docs and still think this is a bug

Bug

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.8.2
            pydantic compiled: True
                 install path: /pathto/.local/share/virtualenvs/project/lib/python3.8/site-packages/pydantic
               python version: 3.8.5 (default, May 27 2021, 13:30:53)  [GCC 9.3.0]
                     platform: Linux-5.8.0-55-generic-x86_64-with-glibc2.29
     optional deps. installed: ['typing-extensions']

When using a Union Type with Submodels for a field in a Settings class, reading from environment for this field is raising an error.
E.g.:

from pydantic import BaseSettings

class A(BaseSettings):
    a: int

class B(BaseSettings):
    b: str

class S(BaseSettings):
    sub: Union[A, B]

raises

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "pydantic/env_settings.py", line 36, in pydantic.env_settings.BaseSettings.__init__
  File "pydantic/main.py", line 406, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 2 validation errors for S
sub
  value is not a valid dict (type=type_error.dict)
sub
  value is not a valid dict (type=type_error.dict)

when calling S() with environment os.environ['sub'] = '{"b": "text"}' .

By introducing a "Middle" class like

class Middle(BaseSettings):
    sub: Union[A, B]

class S(BaseSettings):
    middle: Middle

reading from environment is working like expected with os.environ['middle'] = '{"sub": {"b": "text"}}' .

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V1Bug related to Pydantic V1.X

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions