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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With