ctenar
ctenar

Reputation: 808

How to iterate over all values of an Enum including any nested Enums?

Imagine one has two classes derived from Enum, e.g.

class Color(Enum):
    blue = 'blue'
    red = 'red'

class Properties(Enum):
    height = 'h'
    weight = 'w'
    colors = Color

What is the best way to (probably recursively) iterate over all Enum-labels of a nested Enum like Properties, including the ones of Enum-members like Properties.colors in the example above (i.e. including Color.blue and Color.red)? Checking for the type of the value?

Upvotes: 10

Views: 16791

Answers (2)

pykam
pykam

Reputation: 1481

Doing it recursively is probably the best way. This example is slightly cleaner than using a try except block

import inspect

def iter_enum(e):
  for member in e:  
    if inspect.isclass(member.value) and issubclass(member.value, enum.Enum):
        iter_enum(member.value)
    else:
        print(member)

iter_enum(Properties)

Output

Properties.height
Properties.weight
Color.blue
Color.red

Upvotes: 2

Samwise
Samwise

Reputation: 71464

Here's a quick example that just prints them out. I'll leave it as an exercise to the reader to make this a generic generator or whatever applies to the actual use case. :)

>>> from typing import Type
>>> def print_enum(e: Type[Enum]) -> None:
...     for p in e:
...         try:
...             assert(issubclass(p.value, Enum))
...             print_enum(p.value)
...         except (AssertionError, TypeError):
...             print(p)
...
>>> print_enum(Properties)
Properties.height
Properties.weight
Color.blue
Color.red

Upvotes: 5

Related Questions