Given the following enum:
JavaScript
x
6
1
class MyEnum(IntEnum):
2
3
A = 0
4
B = 1
5
C = 2
6
How can I specify a default value. I want to be able to do:
JavaScript
1
2
1
my_val = MyEnum()
2
and havemy_val
be <MyEnum.A: 0>
Is this possible? I’ve tried customizing __new__
, __init__
, __call__
but I can’t get it to work.
Advertisement
Answer
MyEnum(..)
is handled by EnumMeta.__call__
. You need to override that method:
JavaScript
1
25
25
1
from enum import EnumMeta, IntEnum
2
3
4
class DefaultEnumMeta(EnumMeta):
5
default = object()
6
7
def __call__(cls, value=default, *args, **kwargs):
8
if value is DefaultEnumMeta.default:
9
# Assume the first enum is default
10
return next(iter(cls))
11
return super().__call__(value, *args, **kwargs)
12
# return super(DefaultEnumMeta, cls).__call__(value, *args, **kwargs) # PY2
13
14
15
class MyEnum(IntEnum, metaclass=DefaultEnumMeta):
16
# __metaclass__ = DefaultEnumMeta # PY2 with enum34
17
A = 0
18
B = 1
19
C = 2
20
21
22
assert MyEnum() is MyEnum.A
23
assert MyEnum(0) is MyEnum.A
24
assert MyEnum(1) is not MyEnum.A
25