[Python-checkins] [3.9] bpo-41789: honor object overrides in Enum classes (GH-22250) (GH-22272)

Ethan Furman webhook-mailer at python.org
Wed Sep 16 06:58:54 EDT 2020


https://github.com/python/cpython/commit/a4677068dd61662f5a56b184d5e3aa07db65b88e
commit: a4677068dd61662f5a56b184d5e3aa07db65b88e
branch: 3.9
author: Ethan Furman <ethan at stoneleaf.us>
committer: GitHub <noreply at github.com>
date: 2020-09-16T03:58:33-07:00
summary:

[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.

files:
A Misc/NEWS.d/next/Library/2020-09-14-19-27-46.bpo-41789.pI_uZQ.rst
M Lib/enum.py
M Lib/test/test_enum.py

diff --git a/Lib/enum.py b/Lib/enum.py
index 9dfba3c37cd2c..8711558448107 100644
--- a/Lib/enum.py
+++ b/Lib/enum.py
@@ -249,7 +249,11 @@ def __new__(metacls, cls, bases, classdict):
 
         # 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 b505a6ed13423..0983513d58147 100644
--- a/Lib/test/test_enum.py
+++ b/Lib/test/test_enum.py
@@ -552,6 +552,14 @@ def test_format_enum_str(self):
         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):
@@ -594,7 +602,6 @@ def repr(self):
             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 0000000000000..5ce7a3ca67b72
--- /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__`).



More information about the Python-checkins mailing list