Skip to content

StrEnum isn't coerced into str when used with a Literal #9276

@JesseDeLoore

Description

@JesseDeLoore

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

When using a type of string Literals, passing a StrEnum value is not coerced to the string value of the enum.
In v1 this worked.
It could be a configuration issue, but if so I'm not sure which one.

Example Code

from typing import Literal
import enum

import pydantic
from pydantic import ConfigDict


class Alphabet(enum.StrEnum):
    Z = "Z"
    Y = "Y"
    X = "X"

class TheBestLetters(pydantic.BaseModel):
    model_config = ConfigDict(use_enum_values=True)
    value: Literal["C", "X"]

print(TheBestLetters(value="C"))
print(TheBestLetters(value=Alphabet.X))

outputs

value='C'
Traceback (most recent call last):
  File "C:\Users\ZD6189\AppData\Roaming\JetBrains\PyCharm2024.1\scratches\test_pydantic_enums_2.py", line 18, in <module>
    print(TheBestLetters(value=Alphabet.X))
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\ZD6189\.venv\geco-311\Lib\site-packages\pydantic\main.py", line 175, in __init__
    self.__pydantic_validator__.validate_python(data, self_instance=self)
pydantic_core._pydantic_core.ValidationError: 1 validation error for TheBestLetters
value
  Input should be 'C' or 'X' [type=literal_error, input_value=<Alphabet.X: 'X'>, input_type=Alphabet]
    For further information visit https://errors.pydantic.dev/2.7/v/literal_error

expected output:

value='C'
value='X'

Python, Pydantic & OS Version

pydantic version: 2.7.0
        pydantic-core version: 2.18.1
          pydantic-core build: profile=release pgo=true
                 install path: C:\Users\ZD6189\.venv\geco-311\Lib\site-packages\pydantic
               python version: 3.11.6 (tags/v3.11.6:8b6ee5b, Oct  2 2023, 14:57:12) [MSC v.1935 64 bit (AMD64)]
                     platform: Windows-10-10.0.19045-SP0
             related packages: email-validator-1.3.1 typing_extensions-4.10.0
                       commit: unknown

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions