1

I've had a hard time finding examples of OO Enum composition in Python. So I wanted to ask if the following example is correct or more pythonic ways are advisable?

I prefer class syntax in declaring Enum but it seems for composition Functional API is advisable. Any way to do this using class syntax?

from enum import Enum


class Vertical(Enum):

    Tall = 1
    Short = 2


class Horizontal(Enum):

    Slim = 1
    Spacious = 2


composition = list(Vertical.__members__)
composition.extend(Horizontal.__members__)

Body = Enum('Body', composition)
2
  • 1
    Are you aware that with the above code: Vertical.Tall is Body.Tall is False? Commented Jan 4, 2019 at 21:20
  • Yes I am aware sir. But composition is cognitively so intuitive I will rather figure out a workaround for the truth test than give up on object composition. More so, when modeling natural discreet data focused on domain analyses, because a bottom-up approach would always start with Enum. Commented Jan 4, 2019 at 21:38

1 Answer 1

1

You cannot derive enums, they are "sealed":

class Body(Vertical): pass

leads to TypeError: Cannot extend enumerations.


If you want your composed enums to compare equal you can use IntEnums:

from enum import IntEnum 

class Vertical(IntEnum ):
    Tall = 1
    Short = 2 

class Horizontal(IntEnum):  # distinct int's
    Slim = 3
    Spacious = 4 

composition = list(Vertical.__members__)
composition.extend(Horizontal.__members__)

Body = IntEnum('Body', composition)

Usage:

print(Body.Tall == Vertical.Tall)  # True
print(Body.Tall == 1)              # Also True

Essentially it boils down to : your enums are now also int's. You need to take care to not give the same integer to different concepts though:

class Sizes(IntEnum):
    Tiny = 1

print(Sizes.Tiny == Vertical.Tall)  # True - but not really?
Sign up to request clarification or add additional context in comments.

1 Comment

Ontologically, this is correct. Man.Tall is Building.Tall is False. But Man.Tall == Building.Tall is True. (They are not the same, but both are Tall.) And your solution provides both == syntax comparison, and is difference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.