I have an enum class:
import enum
class Version(enum.IntEnum):
VERSION_1 = 1
VERSION_2 = 2
VERSION_UNKNOWN = 99
When a user initializes the enum class with a value that is not listed as a class field, I would like him to get VERSION_UNKNOWN i.e. the following snippet to execute successfully:
e = enum(3)
assert e == Version.VERSION_UNKNOWN
Is there any way to do that sort of thing?
>Solution :
i think the enum build-in _missing_ is your friend: https://docs.python.org/3/library/enum.html#enum.Enum._missing_
import enum
class Version(enum.IntEnum):
VERSION_1 = 1
VERSION_2 = 2
VERSION_UNKNOWN = 99
@classmethod
def _missing_(cls, value):
return Version.VERSION_UNKNOWN