Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork33.7k
Description
In this StackOverflowanswer, Ethan Furman, the author of theenum module, demonstrated how a tuple value isspecial-cased so that it can beunpacked 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:
fromenumimportEnumclassLabelledEnumMixin:labels= {}def__new__(cls,value,label):member=object.__new__(cls)member._value_=valuemember.label=labelcls.labels[value]=labelreturnmember@classmethoddeflist_labels(cls):returnlist(lforc,lincls.labels.items())classTest(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 theSupported__dunder__ names section of theenum'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.