gh-114071: [Enum] update docs and code for tuples/subclasses (GH-114871)

Update documentation with `__new__` and `__init__` entries.

Support use of `auto()` in tuple subclasses on member assignment lines.  Previously, auto() was only supported on the member definition line either solo or as part of a tuple:

    RED = auto()
    BLUE = auto(), 'azul'

However, since Python itself supports using tuple subclasses where tuples are expected, e.g.:

    from collections import namedtuple
    T = namedtuple('T', 'first second third')

    def test(one, two, three):
        print(one, two, three)

    test(*T(4, 5, 6))
    # 4 5 6

it made sense to also support tuple subclasses in enum definitions.
This commit is contained in:
Ethan Furman 2024-02-04 07:22:55 -08:00 committed by GitHub
parent ec69e1d0dd
commit ff7588b729
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 69 additions and 5 deletions

View file

@ -2344,6 +2344,40 @@ class TestSpecial(unittest.TestCase):
globals()['SomeTuple'] = SomeTuple
test_pickle_dump_load(self.assertIs, SomeTuple.first)
def test_tuple_subclass_with_auto_1(self):
from collections import namedtuple
T = namedtuple('T', 'index desc')
class SomeEnum(T, Enum):
__qualname__ = 'SomeEnum' # needed for pickle protocol 4
first = auto(), 'for the money'
second = auto(), 'for the show'
third = auto(), 'for the music'
self.assertIs(type(SomeEnum.first), SomeEnum)
self.assertEqual(SomeEnum.third.value, (3, 'for the music'))
self.assertIsInstance(SomeEnum.third.value, T)
self.assertEqual(SomeEnum.first.index, 1)
self.assertEqual(SomeEnum.second.desc, 'for the show')
globals()['SomeEnum'] = SomeEnum
globals()['T'] = T
test_pickle_dump_load(self.assertIs, SomeEnum.first)
def test_tuple_subclass_with_auto_2(self):
from collections import namedtuple
T = namedtuple('T', 'index desc')
class SomeEnum(Enum):
__qualname__ = 'SomeEnum' # needed for pickle protocol 4
first = T(auto(), 'for the money')
second = T(auto(), 'for the show')
third = T(auto(), 'for the music')
self.assertIs(type(SomeEnum.first), SomeEnum)
self.assertEqual(SomeEnum.third.value, (3, 'for the music'))
self.assertIsInstance(SomeEnum.third.value, T)
self.assertEqual(SomeEnum.first.value.index, 1)
self.assertEqual(SomeEnum.second.value.desc, 'for the show')
globals()['SomeEnum'] = SomeEnum
globals()['T'] = T
test_pickle_dump_load(self.assertIs, SomeEnum.first)
def test_duplicate_values_give_unique_enum_items(self):
class AutoNumber(Enum):
first = ()