Documentation
This issue is related to #114071 and @ethanfurman suggested creating an isolated issue:
The handling of NamedTuple with a custom Enum is unexpected. Here are two examples that seek to achieve the same thing, but one will fail when using NamedTuple.
Using dataclasses (works):
Details
from dataclasses import dataclass
from enum import Enum
@dataclass
class CodeLabel:
code: int
label: str
class LabelledEnumMixin:
labels = {}
def __new__(cls, codelabel: CodeLabel):
member = object.__new__(cls)
member._value_ = codelabel.code
member.label = codelabel.label
cls.labels[codelabel.code] = codelabel.label
return member
@classmethod
def list_labels(cls):
return list(l for c, l in cls.labels.items())
class Test(LabelledEnumMixin, Enum):
A = CodeLabel(1, "Label A")
B = CodeLabel(2, "Custom B")
C = CodeLabel(3, "Custom label for value C + another string")
Test.list_labels()
Using NamedTuple (fails):
Details
from typing import NamedTuple
from enum import Enum
class CodeLabel(NamedTuple):
code: int
label: str
class LabelledEnumMixin:
labels = {}
def __new__(cls, codelabel: CodeLabel):
member = object.__new__(cls)
member._value_ = codelabel.code
member.label = codelabel.label
cls.labels[codelabel.code] = codelabel.label
return member
@classmethod
def list_labels(cls):
return list(l for c, l in cls.labels.items())
class Test(LabelledEnumMixin, Enum):
A = CodeLabel(1, "Label A")
B = CodeLabel(2, "Custom B")
C = CodeLabel(3, "Custom label for value C + another string")
Test.list_labels()
Linked PRs
Documentation
This issue is related to #114071 and @ethanfurman suggested creating an isolated issue:
The handling of NamedTuple with a custom Enum is unexpected. Here are two examples that seek to achieve the same thing, but one will fail when using NamedTuple.
Using dataclasses (works):
Details
Using NamedTuple (fails):
Details
Linked PRs