Skip to content

Commit 22415ad

Browse files
authored
bpo-41789: honor object overrides in Enum classes (GH-22250)
EnumMeta double-checks that `__repr__`, `__str__`, `__format__`, and `__reduce_ex__` are not the same as `object`'s, and replaces them if they are -- even if that replacement was intentionally done in the Enum being constructed. This patch fixes that. Automerge-Triggered-By: @ethanfurman
1 parent 47f6ec4 commit 22415ad

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

Lib/enum.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,11 @@ def __new__(metacls, cls, bases, classdict):
250250

251251
# double check that repr and friends are not the mixin's or various
252252
# things break (such as pickle)
253+
# however, if the method is defined in the Enum itself, don't replace
254+
# it
253255
for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'):
256+
if name in classdict:
257+
continue
254258
class_method = getattr(enum_class, name)
255259
obj_method = getattr(member_type, name, None)
256260
enum_method = getattr(first_enum, name, None)

Lib/test/test_enum.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -560,6 +560,14 @@ def test_format_enum_str(self):
560560
self.assertFormatIsValue('{:>20}', Directional.WEST)
561561
self.assertFormatIsValue('{:<20}', Directional.WEST)
562562

563+
def test_object_str_override(self):
564+
class Colors(Enum):
565+
RED, GREEN, BLUE = 1, 2, 3
566+
def __repr__(self):
567+
return "test.%s" % (self._name_, )
568+
__str__ = object.__str__
569+
self.assertEqual(str(Colors.RED), 'test.RED')
570+
563571
def test_enum_str_override(self):
564572
class MyStrEnum(Enum):
565573
def __str__(self):
@@ -602,7 +610,6 @@ def repr(self):
602610
class Huh(MyStr, MyInt, Enum):
603611
One = 1
604612

605-
606613
def test_hash(self):
607614
Season = self.Season
608615
dates = {}
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Honor `object` overrides in `Enum` class creation (specifically, `__str__`,
2+
`__repr__`, `__format__`, and `__reduce_ex__`).

0 commit comments

Comments
 (0)