The typesafe enum pattern which was used in Java pre-JDK 5 has a
number of advantages. Much like in Alexandru's answer, you create a
class and class level fields are the enum values; however, the enum
values are instances of the class rather than small integers. This has
the advantage that your enum values don't inadvertently compare equal
to small integers, you can control how they're printed, add arbitrary
methods if that's useful and make assertions using isinstance:
class Animal:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return "" % self
Animal.DOG = Animal("dog")
Animal.CAT = Animal("cat")
>>> x = Animal.DOG
>>> x
>>> x == 1
False
A recent thread on python-dev pointed out there are a couple of enum libraries in the wild, including:
- flufl.enum
- lazr.enum
- ... and the imaginatively named enum