Home > Software design >  Nested enum in Python
Nested enum in Python

Time:08-09

I'm working with regex patterns for several categories and want to encapsulate them in a nested enum. What I liked of mixing in a str type is that the value is immediately available, without .value, such as:

class Colours(str, Enum):
    RED = 'red'

Colours.RED == 'red'
>>> True

I want have this feature in a nested enum but I'm not sure if this is possible.

class Blues(str, Enum):
    DARKBLUE = 'darkblue'
    LIGHTBLUE = 'lightblue'

class Colours(Enum):
    RED = 'red'
    BLUE = Blues

Colours.RED == 'red'
>>> False
Colours.BLUE.DARKBLUE == 'darkblue'  # I would like this is be True
>>> AttributeError: 'Colours' object has no attribute 'DARKBLUE'
Colours.BLUE.value.DARKBLUE.value == 'darkblue'
>>> True

CodePudding user response:

One option to remove the Enum entirely:

class Blues:
    DARKBLUE = 'darkblue'
    LIGHTBLUE = 'lightblue'


class Colours:
    RED = 'red'
    BLUE = Blues


print(Blues.DARKBLUE)  # Blues.DARKBLUE
print(Colours.BLUE.DARKBLUE)  # Blues.DARKBLUE

CodePudding user response:

Getting rid of the inheritances seems to work (using python v3.10)

class Blues:
    DARKBLUE = "darkblue"
    LIGHTBLUE = "lightblue"


class Colours:
    RED = "red"
    BLUE = Blues


print(Colours.BLUE.DARKBLUE == "darkblue")
>>> True

The same should also work if you use dataclasses.

  • Related