diff --git a/Lib/enum.py b/Lib/enum.py index 40ff25b9cdad37..04f2fccafa6c5d 100644 --- a/Lib/enum.py +++ b/Lib/enum.py @@ -785,7 +785,7 @@ def __contains__(self, other): def __iter__(self): members, extra_flags = _decompose(self.__class__, self.value) - return (m for m in members if m._value_ != 0) + return (m for m in members if m._value_.bit_count() == 1) def __repr__(self): cls = self.__class__ diff --git a/Lib/test/test_enum.py b/Lib/test/test_enum.py index 3431040f98a726..f6ba03aadd2bfa 100644 --- a/Lib/test/test_enum.py +++ b/Lib/test/test_enum.py @@ -2413,6 +2413,17 @@ def test_member_iter(self): self.assertEqual(list(Color.BLUE), [Color.BLUE]) self.assertEqual(list(Color.GREEN), [Color.GREEN]) + def test_member_iter_one_bit(self): + class Foo(Flag): + NONE = 0 + A = 1 + B = 2 + C = 4 + AB = A | B + ABC = A | B | C + + self.assertEqual(list(Foo.ABC), [Foo.C, Foo.B, Foo.A]) + def test_auto_number(self): class Color(Flag): red = auto() diff --git a/Misc/NEWS.d/next/Library/2020-11-18-22-38-23.bpo-32218.hCjZSQ.rst b/Misc/NEWS.d/next/Library/2020-11-18-22-38-23.bpo-32218.hCjZSQ.rst new file mode 100644 index 00000000000000..0f299a270dd11c --- /dev/null +++ b/Misc/NEWS.d/next/Library/2020-11-18-22-38-23.bpo-32218.hCjZSQ.rst @@ -0,0 +1,2 @@ +Only keep the single-bit members for :meth:`enum.Flag.__iter__` in :mod:`enum`. +Patch by Weipeng Hong.