Skip to content

Different behaviour when using Literal and Enum and StrEnum #9791

@kwint

Description

@kwint

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

Given the code below, I would have expected the "NormalEnum" to behave the same with and without the literal

Example Code

from pydantic import BaseModel, Field, ConfigDict
from enum import Enum, auto, StrEnum

class NormalEnum(Enum):
     FOO = 'foo'
     BAR = 'bar'

class StringEnum(str, Enum):
     FOO = 'foo'
     BAR = 'bar'

class MyModel(BaseModel):
     a: Literal[NormalEnum.FOO]
     b: Literal[StringEnum.FOO]
     x: NormalEnum
     y: StringEnum

MyModel(a="foo", b="foo", x="foo", y="foo")

"""
ValidationError: 1 validation error for MyModel
a
  Input should be <NormalEnum.FOO: 'foo'> [type=literal_error, input_value='foo', input_type=str]
    For further information visit https://errors.pydantic.dev/2.5/v/literal_error
"""

Python, Pydantic & OS Version

pydantic version: 2.5.3
        pydantic-core version: 2.14.6
          pydantic-core build: profile=release pgo=true
                 install path: /home/kwint/.cache/pypoetry/virtualenvs/metal-hub-jjjW8uEz-py3.11/lib/python3.11/site-packages/pydantic
               python version: 3.11.8 (main, Feb 25 2024, 16:39:33) [GCC 11.4.0]
                     platform: Linux-5.15.153.1-microsoft-standard-WSL2-x86_64-with-glibc2.35
             related packages: pyright-1.1.362 typing_extensions-4.11.0 mypy-1.10.0

Metadata

Metadata

Assignees

Labels

bug V2Bug related to Pydantic V2

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions