How can I Iterate over enum Flag alias?

152 views Asked by At

Question

How can I iterate over enum Flag alias?

from enum import Flag

class Color(Flag):
    RED = 1
    BLUE = 2
    GREEN = 4
    WHITE = RED | BLUE | GREEN # <- How do I retrieve this alias?

list(Color) 
# [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 4>]
# How do I include Color.White and other aliases in this list?

From documentation, __iter__ returns only non-alias members.

__iter__(self):
Returns all contained non-alias members
Changed in version 3.11: Aliases are no longer returned during iteration.

1

There are 1 answers

2
Ch3steR On

You can use __members__ to get a mapping of enum name to value.

From python docs:

__members__ is a read-only ordered mapping of member_name:member items. It is only available on the class.

mapping = Color.__members__
# mappingproxy({'RED': <Color.RED: 1>,
#              'BLUE': <Color.BLUE: 2>,
#              'GREEN': <Color.GREEN: 4>,
#              'WHITE': <Color.WHITE: 7>})

colors_list = list(mapping.values())
# [<Color.RED: 1>, <Color.BLUE: 2>, <Color.GREEN: 4>, <Color.WHITE: 7>]

There's a caveat to this though. If you have enum values that are similar then you'd get the same value returned for them.

class Color(Flag):
    RED = 1
    BLUE = 1
print(Color.__members__)
# mappingproxy({'RED': <Color.RED: 1>, 'BLUE': <Color.RED: 1>})

Useful links: Enum HOWTO: Iteration, Enum HOWTO: Duplicating enum members and values