Repository navigation
add __iter__ to enum.Flag members #76399
Description
Activity
I'm proposing to extend enum.Flag member functionality so it is iterable in a manner similar to enum.Flag subclasses.
from enum import Flag, auto class FlagIter(Flag): def __iter__(self): for memeber in self._member_map_.values(): if member in self: yield member class Colour(FlagIter): RED = auto() GREEN = auto() BLUE = auto() YELLOW = RED | GREEN cyan = Colour.GREEN | Colour.Blue print(*Colour) # Colour.RED Colour.GREEN Colour.BLUE Colour.YELLOW # Without the enhancement, 'not iterable' is thrown for these print(*cyan) # Colour.GREEN Colour.BLUE print(*Colour.YELLOW) # Colour.RED Colour.GREEN Colour.YELLOW print(*~Colour.RED) # Colour.GREEN Colour.BLUE
- addedtype-featureA feature request or enhancementA feature request or enhancement
on Dec 5, 2017 This functionality is now in the third-party aenum* library.
Are there any strong use-cases for this behavior such that it should be in the stdlib?
- as of version 2.0.10, available on PyPI, and I am its author
- added3.10 (EOL)end of lifeend of lifestdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directoryand removed3.8 (EOL)end of lifeend of life
on Sep 17, 2020 Problem: What to do when the Flag has compound members?
class Color(Flag): BLACK = 0 RED = 1 GREEN = 2 BLUE = 4 PURPLE = RED|BLUE WHITE = RED|GREEN|BLUE
I think the answer is: only return the single members. So
--> list(Color.WHITE)
[Color.BLUE, Color.GREEN, Color.RED]What does aenum do and has there been any feedback on it?
To me I would see what you suggest as surprising but I don't use enums often (I should use them more!) so take that with a grain of salt, and also surprising != wrong/not good.
Final outcome:
Flaghas been redesigned such that any flag comprised of a single bit is canonical; flags comprised of multiple bits are considered aliases. During iteration only canonical flags are returned.
FlagandIntFlagmembers iterable #22221Flag.__iter__#23368Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields: