OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Creating an enum with members whose attributes can be initialized

  • Thread starter Thread starter bzm3r
  • Start date Start date
B

bzm3r

Guest
From this answer I learned how to create an enum with attributes (i.e. additional data):

Code:
from typing import NamedTuple

class EnumAttr(NamedTuple):
  data: str


class EnumWithAttrs(EnumAttr, Enum):
    GREEN = EnumAttr(data="hello")
    BLUE = EnumAttr(data="world")

EnumWithAttrs.GREEN.data

Code:
"hello"

I would now to do the following:

Code:
EnumWithAttrs.BLUE(data="yellow").data

Code:
'yellow'

Put differently: I want to be able to do the following:

Code:
a = EnumWithAttrs.BLUE(data="yellow")
b = EnumWithAttrs.BLUE(data="red")

I tried the following (and various variants of it), but it does not work:

Code:
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

Code:
''
<p>From <a href="https://stackoverflow.com/a/62601113/3486684">this answer</a> I learned how to create an enum with attributes (i.e. additional data):</p>
<pre><code>from typing import NamedTuple

class EnumAttr(NamedTuple):
data: str


class EnumWithAttrs(EnumAttr, Enum):
GREEN = EnumAttr(data="hello")
BLUE = EnumAttr(data="world")

EnumWithAttrs.GREEN.data
</code></pre>
<pre><code>"hello"
</code></pre>
<p>I would now to do the following:</p>
<pre class="lang-py prettyprint-override"><code>EnumWithAttrs.BLUE(data="yellow").data
</code></pre>
<pre><code>'yellow'
</code></pre>
<p>Put differently: I want to be able to do the following:</p>
<pre><code>a = EnumWithAttrs.BLUE(data="yellow")
b = EnumWithAttrs.BLUE(data="red")
</code></pre>
<p>I tried the following (and various variants of it), but it does not work:</p>
<pre class="lang-py prettyprint-override"><code>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
</code></pre>
<pre><code>''
</code></pre>
 
Top