Skip to content

Document tuples and __new__ #114071

Closed
Closed
@blhsing

Description

@blhsing

In this StackOverflow answer, Ethan Furman, the author of the enum module, demonstrated how a tuple value is special-cased so that it can be unpacked as arguments to the constructor of the mixin type, making it possible to extremely elegantly implement a member type with additional information such as a label for each member as requested by the SO question:

from enum import Enum

class LabelledEnumMixin:

    labels = {}

    def __new__(cls, value, label):
        member = object.__new__(cls)
        member._value_ = value
        member.label = label
        cls.labels[value] = label
        return member

    @classmethod
    def list_labels(cls):
        return list(l for c, l in cls.labels.items())


class Test(LabelledEnumMixin, Enum):
    A = 1, "Label A"
    B = 2, "Custom B"
    C = 3, "Custom label for value C + another string"

print(list(Test))
print(Test.list_labels())

This outputs:

[<Test.A: 1>, <Test.B: 2>, <Test.C: 3>]
['Label A', 'Custom B', 'Custom label for value C + another string']

Such a neat behavior of a tuple value is currently undocumented in the Supported __dunder__ names section of the enum's docs, however, making it more of an implementation detail rather than a publicly usable feature.

Please help document this feature properly so we can all benefit from the new possibilities this feature enables without fearing that we are using an undocumented implementation detail. Thanks.

Linked PRs

Metadata

Metadata

Assignees

Labels

docsDocumentation in the Doc dir

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions