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.
This commit is contained in:
Ethan Furman 2020-12-10 12:20:06 -08:00 committed by GitHub
parent 9fc571359a
commit efb13be72c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 17 additions and 2 deletions

View File

@ -67,10 +67,12 @@ helper, :class:`auto`.
.. 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.6 ``Flag``, ``IntFlag``, ``auto``
.. versionadded:: 3.10 ``StrEnum``
Creating an Enum Creating an Enum
---------------- ----------------

View File

@ -826,6 +826,12 @@ class StrEnum(str, Enum):
__str__ = str.__str__ __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): def _reduce_ex_by_name(self, proto):
return self.name return self.name

View File

@ -2179,6 +2179,12 @@ class TestEnum(unittest.TestCase):
self.assertEqual(Private._Private__corporal, 'Radar') self.assertEqual(Private._Private__corporal, 'Radar')
self.assertEqual(Private._Private__major_, 'Hoolihan') 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): class TestOrder(unittest.TestCase):

View File

@ -0,0 +1 @@
StrEnum: fix _generate_next_value_ to return a str