Skip to content

Discriminated union does not work with aliased literal field #3849

@ljnsn

Description

@ljnsn

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: /home/ljnsn/.virtualenvs/py39/lib/python3.9/site-packages/
pydantic
               python version: 3.9.7 (default, Sep 10 2021, 14:59:43)  [GCC 11.2.0]
                     platform: Linux-5.15.23-76051523-generic-x86_64-with-glibc2.34
     optional deps. installed: ['typing-extensions']

It seems like the discriminator field for a discriminated union is only recognized when it is passed by its alias, even when allow_population_by_field_name = True. I would expect to be able to pass the discriminator field by field name, just like any other field, when that config option is set.

from typing import Literal, Union

from pydantic import BaseModel, Field


class Base(BaseModel):
    class Config:
        allow_population_by_field_name = True


class Cat(Base):
    pet_type: Literal["cat"] = Field(alias="petType")
    meows: int


class Dog(Base):
    pet_type: Literal["dog"] = Field(alias="petType")
    barks: float


class Lizard(Base):
    pet_type: Literal["reptile", "lizard"] = Field(alias="petType")
    scales: bool


class Model(Base):
    pet: Union[Cat, Dog, Lizard] = Field(..., discriminator="pet_type")
    n: int


print(Dog(**{"pet_type": "dog", "barks": 3.14}))

print(Model(pet={"petType": "dog", "barks": 3.14}, n=1))

print(Model(pet={"pet_type": "dog", "barks": 3.14}, n=1))
# > pydantic.error_wrappers.ValidationError: 1 validation error for Model pet
#   Discriminator 'pet_type' is missing in value (type=value_error.discriminated_union.miss
#   ing_discriminator; discriminator_key=pet_type)

Metadata

Metadata

Labels

bug V1Bug related to Pydantic V1.X

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions