Enum: make `Flag` and `IntFlag` members iterable (GH-22221)
This commit is contained in:
parent
fc23a9483e
commit
7219e27087
|
@ -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
|
||||
^^^^
|
||||
|
@ -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
|
||||
|
|
|
@ -753,6 +753,10 @@ class Flag(Enum):
|
|||
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:
|
||||
|
|
|
@ -2350,6 +2350,12 @@ class TestFlag(unittest.TestCase):
|
|||
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()
|
||||
|
@ -2805,6 +2811,12 @@ class TestIntFlag(unittest.TestCase):
|
|||
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:
|
||||
|
|
|
@ -0,0 +1 @@
|
|||
`enum.Flag` and `enum.IntFlag` members are now iterable
|
Loading…
Reference in New Issue