Update
As of aenum 2.2.11 calling an Enum without a value is supported:
from aenum import Enum, no_arg
class Color(Enum):
black = 0
red = 1
green = 2
blue = 3
#
@classmethod
def _missing_value_(cls, value):
if value is no_arg:
return cls.black
and in use:
>>> Color(1)
<Color.red: 1>
>>> Color()
<Color.black: 0>
>>> Color(4)
Traceback (most recent call last):
...
ValueError: 4 is not a valid Color
Original Answer
If you do not control the Enums, then do:
my_val = list(MyEnum)[0]
or, if the Enum might be empty:
my_val = len(MyEnum) and list(MyEnum)[0] or None
If you do control the Enums, then add a get_default method:
class MyEnum(Enum):
def get_default(self):
return self.A
or, even simpler, make default be an alias:
class MyEnum(Enum):
A = 0
B = 1
C = 2
default = A
You could also wrap the first method in to a function:
def default_member(enum):
return list(enum)[0]
1 Disclosure: I am the author of the Python stdlib Enum, the enum34 backport, and the Advanced Enumeration (aenum) library.
my_valto be the enum valueA? Don't you wantmy_valto be an instance ofMyEnum?my_val = MyEnum()and have the result be the same as doingmy_val = MyEnum(0)_missing_function; According to the documentation"_missing_– a lookup function used when a value is not found; may be overridden"