-
- Notifications
You must be signed in to change notification settings - Fork 33.6k
Closed
Labels
3.11only security fixesonly security fixes3.12only security fixesonly security fixes3.13bugs and security fixesbugs and security fixesstdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error
Description
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):
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):
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
- gh-114149: fix tuple subclass handling when using custom __new__ #114160
- [3.12] gh-114149: [Enum] fix tuple subclass handling when using custom __new__ (GH-114160) #114196
- [3.11] gh-114149: [Enum] fix tuple subclass handling when using custom __new__ (GH-114160) #114197
- gh-114149: [Enum] revert #114160 and add more tuple-subclass tests #114215
- [3.12] gh-114149: [Enum] revert GH-114196 and add more tuple-subclass tests (GH-114215) #114218
Metadata
Metadata
Assignees
Labels
3.11only security fixesonly security fixes3.12only security fixesonly security fixes3.13bugs and security fixesbugs and security fixesstdlibStandard Library Python modules in the Lib/ directoryStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or errorAn unexpected behavior, bug, or error