Skip to content

Commit 05b32c1

Browse files
authored
gh-93820: Fix copy() regression in enum.Flag (GH-93876)
GH-26658 introduced a regression in copy / pickle protocol for combined `enum.Flag`s. `copy.copy(re.A | re.I)` would fail with `AttributeError: ASCII|IGNORECASE`. `enum.Flag` now has a `__reduce_ex__()` method that reduces flags by combined value, not by combined name.
1 parent 8ba1c7f commit 05b32c1

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

Lib/enum.py

+3
Original file line numberDiff line numberDiff line change
@@ -1369,6 +1369,9 @@ class Flag(Enum, boundary=STRICT):
13691369
Support for flags
13701370
"""
13711371

1372+
def __reduce_ex__(self, proto):
1373+
return self.__class__, (self._value_, )
1374+
13721375
_numeric_repr_ = repr
13731376

13741377
def _generate_next_value_(name, start, count, last_values):

Lib/test/test_enum.py

+28
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import copy
12
import enum
23
import doctest
34
import inspect
@@ -734,6 +735,13 @@ def test_format_specs(self):
734735
self.assertFormatIsValue('{:5.2}', TE.third)
735736
self.assertFormatIsValue('{:f}', TE.third)
736737

738+
def test_copy(self):
739+
TE = self.MainEnum
740+
copied = copy.copy(TE)
741+
self.assertEqual(copied, TE)
742+
deep = copy.deepcopy(TE)
743+
self.assertEqual(deep, TE)
744+
737745

738746
class _FlagTests:
739747

@@ -2654,6 +2662,26 @@ class MyIntFlag(int, Flag):
26542662
self.assertTrue(isinstance(MyIntFlag.ONE | MyIntFlag.TWO, MyIntFlag), MyIntFlag.ONE | MyIntFlag.TWO)
26552663
self.assertTrue(isinstance(MyIntFlag.ONE | 2, MyIntFlag))
26562664

2665+
def test_int_flags_copy(self):
2666+
class MyIntFlag(IntFlag):
2667+
ONE = 1
2668+
TWO = 2
2669+
FOUR = 4
2670+
2671+
flags = MyIntFlag.ONE | MyIntFlag.TWO
2672+
copied = copy.copy(flags)
2673+
deep = copy.deepcopy(flags)
2674+
self.assertEqual(copied, flags)
2675+
self.assertEqual(deep, flags)
2676+
2677+
flags = MyIntFlag.ONE | MyIntFlag.TWO | 8
2678+
copied = copy.copy(flags)
2679+
deep = copy.deepcopy(flags)
2680+
self.assertEqual(copied, flags)
2681+
self.assertEqual(deep, flags)
2682+
self.assertEqual(copied.value, 1 | 2 | 8)
2683+
2684+
26572685
class TestOrder(unittest.TestCase):
26582686
"test usage of the `_order_` attribute"
26592687

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fixed a regression when :func:`copy.copy`-ing :class:`enum.Flag` with
2+
multiple flag members.

0 commit comments

Comments
 (0)