Skip to content

enum.auto should use capitalised enumerable strings #115509

@craigcrawfordcts

Description

@craigcrawfordcts

Bug report

Bug description:

Most languages dictate that the value and the name of the enumerable should be uppercase, for example with Java: https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

In python, a convenience method is provided auto, but neither in the description of StrEnum nor auto is it described that the enumerable values will be the lowercased variant of the enumerable's name.

This results in a failure to parse JSON objects using pydantic where the enumerable uses auto instead of directly defining the string, for example if those enumerable values were serialised in Java they are likely to be uppercased.

This results in a shooting-yourself-in-the-foot scenario if you believe you can just swap out your enum values for auto...

from enum import StrEnum, auto
from pydantic import BaseModel
import pytest

class StringEnumType(StrEnum):
    SOME_STRING = "SOME_STRING"


class AutoEnumType(StrEnum):
    SOME_STRING = auto()


class BaseModelWithStringEnumType(BaseModel):
    some_enum: StringEnumType


class BaseModelWithAutoEnumType(BaseModel):
    some_enum: AutoEnumType

@pytest.mark.parametrize(
    "model",
    [
        (BaseModelWithStringEnumType),(BaseModelWithAutoEnumType)
    ]
)
def test(model: BaseModel):
    model = model.model_validate({
        "some_enum": "SOME_STRING"
    })
tests/unit/test_fail.py::test[BaseModelWithAutoEnumType] FAILED
tests/unit/test_fail.py::test[BaseModelWithStringEnumType] PASSED

================================================================================== FAILURES ===================================================================================
_______________________________________________________________________ test[BaseModelWithAutoEnumType] _______________________________________________________________________

model = <class 'unit.test_fail.BaseModelWithAutoEnumType'>

    @pytest.mark.parametrize(
        "model",
        [
            (BaseModelWithStringEnumType),(BaseModelWithAutoEnumType)
        ]
    )
    def test(model: BaseModel):
>       model = model.model_validate({
            "some_enum": "SOME_STRING"
        })
E       pydantic_core._pydantic_core.ValidationError: 1 validation error for BaseModelWithAutoEnumType
E       some_enum
E         Input should be 'some_string' [type=enum, input_value='SOME_STRING', input_type=str]

tests/unit/test_fail.py:27: ValidationError

CPython versions tested on:

3.11

Operating systems tested on:

Linux

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions