The Python docs for the enum
module contains the following example of subclassing Enum
. The resulting class can be used to create enums that also validate that they have no two members with the same value.
>>> class DuplicateFreeEnum(Enum):
... def __init__(self, *args):
... cls = self.__class__
... if any(self.value == e.value for e in cls):
... a = self.name
... e = cls(self.value).name
... raise ValueError(
... "aliases not allowed in DuplicateFreeEnum: %r --> %r"
... % (a, e))
However, as a method of adding validation, this method is inelegant and restrictive. __init__
is called once for each member, whereas in order to validate an enum as a whole, it makes more sense to look at every member of the enum together.
For instance, how would I validate that an enum has precisely two members, as below?
class PreciselyTwoEnum(Enum):
... # ???
class Allowed(PreciselyTwoEnum):
FOO = 1
BAR = 2
class Disallowed(PreciselyTwoEnum): # Should raise an error
BAZ = 3
Can this be accomplished with a clever implementation of __init__
? Is there another method that could be used — perhaps one that is called on the enum after it has been fully created?