Nested Unique Enums in Python

Viewed 123

I'm trying to create a nested Enum in Python which adheres to the unique constraint and increments with auto() (or has variable name = enum name). I think the best way to do this is to overwrite the iter on the Enum metaclass. I'm trying the following

from enum import Enum, unique, auto


class FinalEnumMeta(type(Enum)):
    def __iter__(cls):
        x=list()
        for name in cls._member_names_:
            x.append(cls._member_map_[name])
        for b in list(cls._member_map_[name] for name in cls._member_names_):
            print(b)
        print(list(cls._member_map_[name] for name in cls._member_names_))
        return (a for a in x)


class _Reading(Enum):
    mispronunciation = auto()


class _Writing(Enum):
    misspelling = auto()


@unique
class Mistake(Enum, metaclass=FinalEnumMeta):
    def __init__(self, param):
        Enum.__init__(self)
    one = auto()
    two = auto()
    three = auto()
    four = auto()
    reading = _Reading
    writing = _Writing

[e for e in Mistake]
The output is as follows:
Mistake.one
Mistake.two
Mistake.three
Mistake.four
Mistake.reading
Mistake.writing
[<Mistake.one: 1>, <Mistake.two: 2>, <Mistake.three: 3>, <Mistake.four: 4>, <Mistake.reading: <enum '_Reading'>>, <Mistake.writing: <enum '_Writing'>>]

How do I look at the generator and arrive at the fact that cls._member_map_[name] is of type enum? More importantly why does the generatpr print differently when in a for loop vs being printed as a list? How do I access the type of Mistake.writing / Mistake.reading and tell iter that it has to go deeper?

0 Answers
Related