Skip to content

(🐞) Enum with multiple values (tuple) can't be round tripped through json #10629

@KotlinIsland

Description

@KotlinIsland

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

pydantic_core._pydantic_core.ValidationError: 1 validation error for RootModel[A]
a
  Input should be (1, 2) [type=enum, input_value=[1, 2], input_type=list]
    For further information visit https://errors.pydantic.dev/2.9/v/enum

Enums support functionality where a tuple ("multiple values") is assigned to the member

here, we see that pydantic does not support serialising and parsing of this type of Enum value

Workaround

add a core schema to the class:

    @classmethod
    def __get_pydantic_core_schema__(cls, source_type, handler):
        return core_schema.no_info_before_validator_function(
            lambda data: data if isinstance(data, cls) else tuple(data), handler(source_type)
        )

Example Code

from enum import Enum

from pydantic import RootModel


class A(Enum):
    a = 1, 2


serialised = RootModel[A](A.a).model_dump_json()
parsed = RootModel[A].model_validate_json(serialised)

Python, Pydantic & OS Version

pydantic version: 2.9.2
        pydantic-core version: 2.23.4
          pydantic-core build: profile=release pgo=false
                 install path: C:\Users\AMONGUS\projects\test\.venv\Lib\site-packages\pydantic
               python version: 3.12.2 (tags/v3.12.2:6abddd9, Feb  6 2024, 21:26:36) [MSC v.1937 64 bit (AMD64)]
                     platform: Windows-10-10.0.19045-SP0
             related packages: typing_extensions-4.12.2
                       commit: unknown

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug V2Bug related to Pydantic V2help wantedPull Request welcometopic-enumsRelated to enums

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions