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:

  1. def enum(**enums):
  2. return type('Enum', (), enums)
  3.  
  4. 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()

  1. from enum import Enum
  2.  
  3. class MyEnum(Enum):
  4. VALUE = 0
  5.  
  6. def __str__(self):
  7. if self.value == MyEnum.VALUE:
  8. return 'Value'
  9. else:
  10. return 'Unknown ({})'.format(self.value)
  11. def __eq__(self,y):
  12. return self.value==y
  13.  
  14. @classmethod
  15. def fromstring(cls, value):
  16. """
  17. Converts string to enum
  18. """
  19.  
  20. return getattr(cls, value.upper(), None)
  21.  
  22. @classmethod
  23. def tostring(cls, val):
  24. """
  25. Converts enum to string
  26. """
  27.  
  28. for k, v in vars(cls).iteritems():
  29. if v == val:
  30. return k

Option 3:

  1. class MyEnum():
  2. NONE = 1
  3. VALUE = 2
  4. def __init__(self, Type):
  5. if Type is None:
  6. self.value = MyEnum.VALUE
  7. else:
  8. self.value = int(Type)
  9. def __str__(self):
  10. if self.value == MyEnum.VALUE:
  11. return 'Value'
  12. else:
  13. return 'None'
  14. def __eq__(self,y):
  15. return self.value==y