how do i override iterations behavior of a enum flag subclass?

You can sublass EnumMeta and then add metaclass= to your Enum class:

from enum import Flag, EnumMeta, auto


class MyEnumMeta(EnumMeta):
    def __iter__(self):
       for x in super().__iter__():
           if x.value % 2 == 0:
                yield x


class MyFlags(Flag, metaclass=MyEnumMeta):
    A = auto()
    B = auto()
    C = auto()
    
    D = A | C


print(list(MyFlags))

Prints:

[<MyFlags.B: 2>, <MyFlags.C: 4>]

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top