Python: Enums

(Last Updated On: )

There are a variety of different ways to create enums. I show you a few different ways. They are not full version but you get the idea. If you have another way please feel free to add.

Option 1:

def enum(**enums):
    return type('Enum', (), enums)

my_enum = enum(NONE=0, SOMEVAL=1, SOMEOTHERVAL=2)

Option 2:
You will notice that you pass in “Enum” into the class. Also this way you can also declare classmethods for getting enum from string or tostring. It’s really your choice how you get the string representation you could either use str(MyEnum.VALUE) or MyEnum.tostring()

from enum import Enum

class MyEnum(Enum):
    VALUE = 0

    def __str__(self):
        if self.value == MyEnum.VALUE:
            return 'Value'
        else:
            return 'Unknown ({})'.format(self.value)
    def __eq__(self,y):
        return self.value==y

    @classmethod
    def fromstring(cls, value):
        """
        Converts string to enum
        """

        return getattr(cls, value.upper(), None)

    @classmethod
    def tostring(cls, val):
        """
        Converts enum to string
        """

        for k, v in vars(cls).iteritems():
            if v == val:
                return k

Option 3:

class MyEnum():
    NONE = 1
    VALUE = 2
    
    def __init__(self, Type):
        if Type is None:
            self.value = MyEnum.VALUE
        else:
            self.value = int(Type)
    def __str__(self):
        if self.value == MyEnum.VALUE:
            return 'Value'
        else:
            return 'None'
    def __eq__(self,y):
        return self.value==y