Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare a static variable in an enum class

I have an enum for colors. I wish to add a helper method "toRGB()" to the enum class that converts an instance of the enum to an RGB object. As an optimization, I wished to create the dictionary once as a static variable. However, the correct syntax seems to elude me.

Can anyone suggest the right way to do this?

from enum import Enum

class RGB:
    def __init__(self, r, g, b):
        pass

class Color(Enum):
    RED = 0
    GREEN = 1

    __tbl = {
              RED:   RGB(1, 0, 0),
              GREEN: RGB(0, 1, 0)
            }

    def toRGB(self):
        return self.__class__.__tbl[self.value]

c = Color.RED
print(c.toRGB())

I get the following error:

Traceback (most recent call last):
  File "C:/Users/user/Desktop/test.py", line 20, in <module>
    print(c.toRGB())
  File "C:/Users/user/Desktop/test.py", line 17, in toRGB
    return self.__class__.__tbl[self.value]
TypeError: 'Color' object does not support indexing
like image 385
fafaro Avatar asked Mar 15 '16 05:03

fafaro


1 Answers

As of Python 3.7, use the _ignore_ field: https://docs.python.org/3/library/enum.html

class Color(Enum):
    _ignore_ = ['_tbl']
    _tbl = {}  # nice for the type checker, but entirely ignored!


Color._tbl = {}  # actually creates the attribute
like image 125
vdboor Avatar answered Sep 30 '22 15:09

vdboor