Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Enum validation doesn't work for custom __new__ methods #9248

Open
1 task done
aikow opened this issue Apr 15, 2024 · 1 comment
Open
1 task done

New Enum validation doesn't work for custom __new__ methods #9248

aikow opened this issue Apr 15, 2024 · 1 comment
Labels
bug V2 Bug related to Pydantic V2

Comments

@aikow
Copy link

aikow commented Apr 15, 2024

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

The newly release improvements to the Enum class break enums with a custom __new__ implementation.

I don't think this is an official intended use case of the Enum class, so I don't have an issue with this if this doesn't get fixed.

A super easy work-around is to use a PlainValidator to just call the constructor in python, not rust.

print(
    TypeAdapter(Annotated[Animal, PlainValidator(lambda s: Animal(s))]).validate_python(
        "meow"
    )
)

Example Code

from enum import Enum
from pydantic import TypeAdapter


class Animal(Enum):
    CAT = "cat", "meow"
    DOG = "dog", "woof"

    def __new__(cls, species: str, sound: str):
        obj = object.__new__(cls)

        obj._value_ = species
        obj._all_values = (species, sound)

        obj.species = species
        obj.sound = sound

        cls._value2member_map_[sound] = obj

        return obj


print(Animal("cat"))
print(Animal("meow"))
print(TypeAdapter(Animal).validate_python("meow"))

Python, Pydantic & OS Version

pydantic version: 2.7.0
        pydantic-core version: 2.18.1
          pydantic-core build: profile=release pgo=false
                 install path: /Users/aikow/.miniconda3/envs/py310-pydantic/lib/python3.10/site-packages/pydantic
               python version: 3.10.14 | packaged by conda-forge | (main, Mar 20 2024, 12:53:34) [Clang 16.0.6 ]
                     platform: macOS-14.4.1-x86_64-i386-64bit
             related packages: typing_extensions-4.11.0
                       commit: unknown
@aikow aikow added bug V2 Bug related to Pydantic V2 pending Awaiting a response / confirmation labels Apr 15, 2024
@samuelcolvin samuelcolvin removed the pending Awaiting a response / confirmation label Apr 16, 2024
@samuelcolvin
Copy link
Member

Makes sense, happy to accept a pr to pydantic-core to detect custom __new__ methods and call them if that's possible.

Btw, we already support the __missing__ if that helps?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug V2 Bug related to Pydantic V2
Projects
None yet
Development

No branches or pull requests

2 participants