]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-42385: [Enum] add `_generate_next_value_` to StrEnum (GH-23735)
authorEthan Furman <ethan@stoneleaf.us>
Thu, 10 Dec 2020 20:20:06 +0000 (12:20 -0800)
committerGitHub <noreply@github.com>
Thu, 10 Dec 2020 20:20:06 +0000 (12:20 -0800)
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.

Doc/library/enum.rst
Lib/enum.py
Lib/test/test_enum.py
Misc/NEWS.d/next/Library/2020-12-09-19-45-32.bpo-42385.boGbjo.rst [new file with mode: 0644]

index a9584b9c91083c4549a0f89b9c86760341a6d2a8..a0b078c971706bd697952672142bed28c77a6d6b 100644 (file)
@@ -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
 ----------------
index 74318c3b71deb4bcdbaf3c44aeff038cbb0bdce4..ed0c9ce72d01c46e913c382b6fe7eed742ff01e8 100644 (file)
@@ -826,6 +826,12 @@ class StrEnum(str, Enum):
 
     __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
index 7ca54e9a649ca8568b3c79b9369feca4d59408cf..f245eb6ccaeeeb70301edd7c60e370cbe0c0e5fd 100644 (file)
@@ -2179,6 +2179,12 @@ class TestEnum(unittest.TestCase):
         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 (file)
index 0000000..f95da85
--- /dev/null
@@ -0,0 +1 @@
+StrEnum: fix _generate_next_value_ to return a str