bad_coder
bad_coder

Reputation: 12870

Enum Composition in Python

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)

Upvotes: 1

Views: 1104

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51623

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?

Upvotes: 1

Related Questions