Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueError when using custom new in Python Enum

Tags:

python

enums

I'm encountering an issue with the following Python code where a ValueError is raised when trying to create an instance of an Enum with a value that doesn't correspond to any defined enum member:

from enum import Enum

class Option(Enum):
    OPTION_1 = "Option 1"
    OPTION_2 = "Option 2"
    NONE = ""

    def __new__(cls, value):
        try:
            obj = object.__new__(cls)
            obj._value_ = value
            return obj
        except ValueError:
            return Option.NONE

tmp = Option("Option 3")

The ValueError seems to be related to how the __new__ method is handling the invalid values. I want the code to create an instance of the NONE member in case an invalid value is provided, but it doesn't seem to be working as expected.

Why is this code resulting in a ValueError and how can I achieve the desired behavior of using the NONE member for invalid values?

like image 543
DomDunk Avatar asked Aug 31 '25 01:08

DomDunk


1 Answers

The __new__ method is used during enum class creation; after that Enum.__new__ is swapped in, and it only does look-ups.

To handle situations like these, use the _missing_ method:

@classmethod
def _missing_(cls, value):
    return cls.NONE

Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.

like image 134
Ethan Furman Avatar answered Sep 03 '25 06:09

Ethan Furman