A Problem with Combined Enum in Python
Try not to use combined Enum if possible
Sometimes we may want to create a combined Enum which includes all the elements of other Enum classes. For example, we may want to create an Enum for the AI models of each AI platform like OpenAI, Gemini, Claude, etc, and use it as a common entry for all the AI models. In this post, we will introduce the problem with such a solution and why we should avoid using it in practice.
Create a combined Enum
In Python, we cannot directly combine two Enum classes in the sense of merging them into a new Enum that contains all members of both. We cannot subclass multiple Enum classes to create a new Enum that inherits members from both either. A feasible solution is to create the combined Enum dynamically using the functional API of Enum.
from enum import IntEnum
class EnumA(IntEnum):
OPTION_A = 1
OPTION_B = 2
class EnumB(IntEnum):
OPTION_C = 3
OPTION_D = 4
CombinedEnum = IntEnum(
"CombinedEnum",
{**EnumA.__members__, **EnumB.__members__},
)
print(EnumA.OPTION_A) # 1
print(EnumB.OPTION_C) # 3
print(CombinedEnum.OPTION_A) # 1
print(CombinedEnum.OPTION_C) # 3
In this solution, we call the Enum
class or its subclass which is IntEnum
in this example as a function and pass the Enum…