Skip to content
Advertisement

Is there a way to specify a default value for python enums?

Given the following enum:

class MyEnum(IntEnum):

    A = 0
    B = 1
    C = 2

How can I specify a default value. I want to be able to do:

my_val = MyEnum()

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:

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
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement