From this answer I learned how to create an enum with attributes (i.e. additional data):
from typing import NamedTuple
class EnumAttr(NamedTuple):
data: str
class EnumWithAttrs(EnumAttr, Enum):
GREEN = EnumAttr(data="hello")
BLUE = EnumAttr(data="world")
EnumWithAttrs.GREEN.data
"hello"
I would now to do the following:
EnumWithAttrs.BLUE(data="yellow").data
'yellow'
Put differently: I want to be able to do the following:
a = EnumWithAttrs.BLUE(data="yellow")
b = EnumWithAttrs.BLUE(data="red")
I tried the following, but it does not work:
from enum import Enum
from typing import Any, Callable, NamedTuple, Self
class EnumAttr(NamedTuple):
data: str = ""
class EnumWithAttrs(EnumAttr, Enum):
GREEN = EnumAttr(data="hello")
BLUE = EnumAttr()
def with_data(self, s: str) -> Self:
self._replace(data=s)
return self
x = EnumWithAttrs.BLUE.with_data("world")
x.data
''