I have an enum subclass where I need to associate two pieces of data with each enum. The first is used for the enum value itself, the second needs to be stored as an attribute.
Here is an example showing what I am trying to do:
What I expect to get is this:
But instead, I get this error:
I have read the docs, but they only show an example where you are subclassing another class as well as Enum:
https://docs.python.org/3/library/enum.h...ew-vs-init
Here is an example showing what I am trying to do:
1 2 3 4 5 6 7 8 |
from enum import Enum class MyEnum(Enum): MEMBER = ( "This is my enum" , 1.5 ) def __new__( cls , value, extra): obj = super ().__new__( cls , value) obj._value_ = value obj.extra = extra return obj |
1 2 |
MyEnum.MEMBER.value = = "This is my enum" # This should return True MyEnum.MEMBER.extra = = 1.5 # This should return True |
Error:Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.10/enum.py", line 288, in __new__
enum_member = __new__(enum_class, *args)
File "<stdin>", line 4, in __new__
File "/usr/local/lib/python3.10/enum.py", line 701, in __new__
raise ve_exc
ValueError: 'This is my enum' is not a valid MyEnum
What is the right way to override __new__
in an Enum? I have read the docs, but they only show an example where you are subclassing another class as well as Enum:
https://docs.python.org/3/library/enum.h...ew-vs-init