[Python-checkins] bpo-42385: [Enum] add `_generate_next_value_` to StrEnum (GH-23735)

ethanfurman webhook-mailer at python.org
Thu Dec 10 15:20:17 EST 2020


https://github.com/python/cpython/commit/efb13be72cbf49edf591936fafb120fe1b7d59f7
commit: efb13be72cbf49edf591936fafb120fe1b7d59f7
branch: master
author: Ethan Furman <ethan at stoneleaf.us>
committer: ethanfurman <ethan at stoneleaf.us>
date: 2020-12-10T12:20:06-08:00
summary:

bpo-42385: [Enum] add `_generate_next_value_` to StrEnum (GH-23735)

The default for auto() is to return an integer, which doesn't work for `StrEnum`.  The new `_generate_next_value_` for `StrEnum` returns the member name, lower cased.

files:
A Misc/NEWS.d/next/Library/2020-12-09-19-45-32.bpo-42385.boGbjo.rst
M Doc/library/enum.rst
M Lib/enum.py
M Lib/test/test_enum.py

diff --git a/Doc/library/enum.rst b/Doc/library/enum.rst
index a9584b9c91083..a0b078c971706 100644
--- a/Doc/library/enum.rst
+++ b/Doc/library/enum.rst
@@ -67,10 +67,12 @@ helper, :class:`auto`.
 
 .. class:: auto
 
-    Instances are replaced with an appropriate value for Enum members.  By default, the initial value starts at 1.
+    Instances are replaced with an appropriate value for Enum members.
+    :class:`StrEnum` defaults to the lower-cased version of the member name,
+    while other Enums default to 1 and increase from there.
 
 .. versionadded:: 3.6  ``Flag``, ``IntFlag``, ``auto``
-
+.. versionadded:: 3.10  ``StrEnum``
 
 Creating an Enum
 ----------------
diff --git a/Lib/enum.py b/Lib/enum.py
index 74318c3b71deb..ed0c9ce72d01c 100644
--- a/Lib/enum.py
+++ b/Lib/enum.py
@@ -826,6 +826,12 @@ def __new__(cls, *values):
 
     __str__ = str.__str__
 
+    def _generate_next_value_(name, start, count, last_values):
+        """
+        Return the lower-cased version of the member name.
+        """
+        return name.lower()
+
 
 def _reduce_ex_by_name(self, proto):
     return self.name
diff --git a/Lib/test/test_enum.py b/Lib/test/test_enum.py
index 7ca54e9a649ca..f245eb6ccaeee 100644
--- a/Lib/test/test_enum.py
+++ b/Lib/test/test_enum.py
@@ -2179,6 +2179,12 @@ class Private(Enum):
         self.assertEqual(Private._Private__corporal, 'Radar')
         self.assertEqual(Private._Private__major_, 'Hoolihan')
 
+    def test_strenum_auto(self):
+        class Strings(StrEnum):
+            ONE = auto()
+            TWO = auto()
+        self.assertEqual([Strings.ONE, Strings.TWO], ['one', 'two'])
+
 
 class TestOrder(unittest.TestCase):
 
diff --git a/Misc/NEWS.d/next/Library/2020-12-09-19-45-32.bpo-42385.boGbjo.rst b/Misc/NEWS.d/next/Library/2020-12-09-19-45-32.bpo-42385.boGbjo.rst
new file mode 100644
index 0000000000000..f95da859b0388
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2020-12-09-19-45-32.bpo-42385.boGbjo.rst
@@ -0,0 +1 @@
+StrEnum: fix _generate_next_value_ to return a str



More information about the Python-checkins mailing list