diff --git a/Lib/enum.py b/Lib/enum.py index 5e0088ee89f..e72d3062674 100644 --- a/Lib/enum.py +++ b/Lib/enum.py @@ -250,7 +250,11 @@ class EnumMeta(type): # double check that repr and friends are not the mixin's or various # things break (such as pickle) + # however, if the method is defined in the Enum itself, don't replace + # it for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'): + if name in classdict: + continue class_method = getattr(enum_class, name) obj_method = getattr(member_type, name, None) enum_method = getattr(first_enum, name, None) diff --git a/Lib/test/test_enum.py b/Lib/test/test_enum.py index a909c108833..865edf1d9cf 100644 --- a/Lib/test/test_enum.py +++ b/Lib/test/test_enum.py @@ -560,6 +560,14 @@ class TestEnum(unittest.TestCase): self.assertFormatIsValue('{:>20}', Directional.WEST) self.assertFormatIsValue('{:<20}', Directional.WEST) + def test_object_str_override(self): + class Colors(Enum): + RED, GREEN, BLUE = 1, 2, 3 + def __repr__(self): + return "test.%s" % (self._name_, ) + __str__ = object.__str__ + self.assertEqual(str(Colors.RED), 'test.RED') + def test_enum_str_override(self): class MyStrEnum(Enum): def __str__(self): @@ -602,7 +610,6 @@ class TestEnum(unittest.TestCase): class Huh(MyStr, MyInt, Enum): One = 1 - def test_hash(self): Season = self.Season dates = {} diff --git a/Misc/NEWS.d/next/Library/2020-09-14-19-27-46.bpo-41789.pI_uZQ.rst b/Misc/NEWS.d/next/Library/2020-09-14-19-27-46.bpo-41789.pI_uZQ.rst new file mode 100644 index 00000000000..5ce7a3ca67b --- /dev/null +++ b/Misc/NEWS.d/next/Library/2020-09-14-19-27-46.bpo-41789.pI_uZQ.rst @@ -0,0 +1,2 @@ +Honor `object` overrides in `Enum` class creation (specifically, `__str__`, +`__repr__`, `__format__`, and `__reduce_ex__`).