Skip to content

Commit

Permalink
Enum: make Flag and IntFlag members iterable (pythonGH-22221)
Browse files Browse the repository at this point in the history
  • Loading branch information
ethanfurman authored and Seth Sims committed Oct 18, 2020
1 parent 30a7ad0 commit a940338
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 0 deletions.
15 changes: 15 additions & 0 deletions Doc/library/enum.rst
Original file line number Diff line number Diff line change
Expand Up @@ -656,6 +656,13 @@ be combined with them::
>>> Perm.X | 8
<Perm.8|X: 9>

:class:`IntFlag` members can also be iterated over::

>>> list(RW)
[<Perm.R: 4>, <Perm.W: 2>]

.. versionadded:: 3.10


Flag
^^^^
Expand Down Expand Up @@ -709,6 +716,14 @@ value::
>>> bool(Color.BLACK)
False

:class:`Flag` members can also be iterated over::

>>> purple = Color.RED | Color.BLUE
>>> list(purple)
[<Color.BLUE: 2>, <Color.RED: 1>]

.. versionadded:: 3.10

.. note::

For the majority of new code, :class:`Enum` and :class:`Flag` are strongly
Expand Down
4 changes: 4 additions & 0 deletions Lib/enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,10 @@ def __contains__(self, other):
type(other).__qualname__, self.__class__.__qualname__))
return other._value_ & self._value_ == other._value_

def __iter__(self):
members, extra_flags = _decompose(self.__class__, self.value)
return (m for m in members if m._value_ != 0)

def __repr__(self):
cls = self.__class__
if self._name_ is not None:
Expand Down
12 changes: 12 additions & 0 deletions Lib/test/test_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -2350,6 +2350,12 @@ def test_member_contains(self):
self.assertFalse(W in RX)
self.assertFalse(X in RW)

def test_member_iter(self):
Color = self.Color
self.assertEqual(list(Color.PURPLE), [Color.BLUE, Color.RED])
self.assertEqual(list(Color.BLUE), [Color.BLUE])
self.assertEqual(list(Color.GREEN), [Color.GREEN])

def test_auto_number(self):
class Color(Flag):
red = auto()
Expand Down Expand Up @@ -2805,6 +2811,12 @@ def test_member_contains(self):
with self.assertRaises(TypeError):
self.assertFalse('test' in RW)

def test_member_iter(self):
Color = self.Color
self.assertEqual(list(Color.PURPLE), [Color.BLUE, Color.RED])
self.assertEqual(list(Color.BLUE), [Color.BLUE])
self.assertEqual(list(Color.GREEN), [Color.GREEN])

def test_bool(self):
Perm = self.Perm
for f in Perm:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`enum.Flag` and `enum.IntFlag` members are now iterable

0 comments on commit a940338

Please sign in to comment.