8000 [3.9] bpo-41789: honor object overrides in Enum classes (GH-22250) (G… · python/cpython@a467706 · GitHub
[go: up one dir, main page]

Skip to content

Commit a467706

Browse files
authored
[3.9] bpo-41789: honor object overrides in Enum classes (GH-22250) (GH-22272)
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.
1 parent 95b81e2 commit a467706

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
@@ -249,7 +249,11 @@ def __new__(metacls, cls, bases, classdict):
249249

250250
# double check that repr and friends are not the mixin's or various
251251
# things break (such as pickle)
252+
# however, if the method is defined in the Enum itself, don't replace
253+
# it
252254
for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'):
255+
if name in classdict:
256+
continue
253257
class_method = getattr(enum_class, name)
254258
obj_method = getattr(member_type, name, None)
255259
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
@@ -552,6 +552,14 @@ def test_format_enum_str(self):
552552
self.assertFormatIsValue('{:>20}', Directional.WEST)
553553
self.assertFormatIsValue('{:<20}', Directional.WEST)
554554

555+
def test_object_str_override(self):
556+
class Colors(Enum):
557+
RED, GREEN, BLUE = 1, 2, 3
558+
def __repr__(self):
559+
return "test.%s" % (self._name_, )
560+
__str__ = object.__str__
561+
self.assertEqual(str(Colors.RED), 'test.RED')
562+
555563
def test_enum_str_override(self):
556564
class MyStrEnum(Enum):
557565
def __str__(self):
@@ -594,7 +602,6 @@ def repr(self):
594602
class Huh(MyStr, MyInt, Enum):
595603
One = 1
596604

597-
598605
def test_hash(self):
599606
Season = self.Season
600607
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)
0