Skip to content

JSON schema generation of Discriminated Unions doesn't work with lists #3608

@adrienyhuel

Description

@adrienyhuel

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.9.0
            pydantic compiled: True
                 install path: C:\Users\Adrien\Documents\GitHub\mft\backend\venv\Lib\site-packages\pydantic
               python version: 3.9.5 (tags/v3.9.5:0a7dcbd, May  3 2021, 17:27:52) [MSC v.1928 64 bit (AMD64)]
                     platform: Windows-10-10.0.19044-SP0
     optional deps. installed: ['dotenv', 'email-validator', 'typing-extensions']

I tested the ne feature "discriminated unions", using the sample at https://pydantic-docs.helpmanual.io/usage/types/#discriminated-unions-aka-tagged-unions, and it works great.

But when I use it in arrays, it doesn't work. The resulting json schema doesn't contains any discriminator.

See here, I modified the sample ( pet: Pet to pet: List[Pet] ) :

from typing import Literal, Union, List
from typing_extensions import Annotated
from pydantic import BaseModel, Field

class BlackCat(BaseModel):
    pet_type: Literal['cat']
    color: Literal['black']
    black_name: str

class WhiteCat(BaseModel):
    pet_type: Literal['cat']
    color: Literal['white']
    white_name: str

Cat = Annotated[Union[BlackCat, WhiteCat], Field(discriminator='color')]

class Dog(BaseModel):
    pet_type: Literal['dog']
    name: str

Pet = Annotated[Union[Cat, Dog], Field(discriminator='pet_type')]

class Model(BaseModel):
    pet: List[Pet]
    n: int

print(Model.schema_json())

...

JSON schema gives :

"pet":{
         "title":"Pet",
         "type":"array",
         "items":{
            "anyOf":[
               {
                  "anyOf":[
                     {
                        "$ref":"#/definitions/BlackCat"
                     },
                     {
                        "$ref":"#/definitions/WhiteCat"
                     }
                  ]
               },
               {
                  "$ref":"#/definitions/Dog"
               }
            ]
         }
      }

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V1Bug related to Pydantic V1.X

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions