Is there a way to specify a default value for python enums?
MyEnum(..)
processed . You need to override this method: EnumMeta.__call__
from enum import EnumMeta, IntEnum
class DefaultEnumMeta(EnumMeta):
default = object()
def __call__(cls, value=default, *args, **kwargs):
if value is DefaultEnumMeta.default:
# Assume the first enum is default
return next(iter(cls))
return super().__call__(value, *args, **kwargs)
# return super(DefaultEnumMeta, cls).__call__(value, *args, **kwargs) # PY2
class MyEnum(IntEnum, metaclass=DefaultEnumMeta):
# __metaclass__ = DefaultEnumMeta # PY2 with enum34
A = 0
B = 1
C = 2
assert MyEnum() is MyEnum.A
assert MyEnum(0) is MyEnum.A
assert MyEnum(1) is not MyEnum.A
source to share
Why aren't you using standard standard syntax ?
my_val = MyEnum.A
If you really want to do this, you might have to write your own enum override class. You can see this example for an implementation in cpython to assign a default equal to the first value in the value map for the enumeration.
source to share
Refresh
Starting from aenum 2.2.1
1 , calling Enum without 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 are not in control Enum
, then do:
my_val = list(MyEnum)[0]
or, if Enum
can be empty:
my_val = len(MyEnum) and list(MyEnum)[0] or None
If you're in control Enum
, add a method get_default
:
class MyEnum(Enum):
def get_default(self):
return self.A
or, even easier, do it by default
alias:
class MyEnum(Enum):
A = 0
B = 1
C = 2
default = A
You can also wrap the first method in a function:
def default_member(enum):
return list(enum)[0]
1 Disclosure: I am the author of the Python stdlibEnum
, and the Advanced Enumeration ( ) library . enum34
aenum
source to share
Falsetru's answer would be a good fit if there are 0 arguments to consider.
If it is only about returning default when the given value does not exist, we can override _missing_
in the Enum class (since Python 3.6 ):
from enum import IntEnum
class MyEnum(IntEnum):
A = 0
B = 1
C = 2
@classmethod
def _missing_(cls, value):
return MyEnum.A
assert MyEnum(0) is MyEnum.A
assert MyEnum(1) is MyEnum.B
assert MyEnum(-1) is MyEnum.A
assert MyEnum(None) is MyEnum.A
source to share