Before PEP 435, Python didn't have an equivalent but you could implement your own.
Myself, I like keeping it simple (I've seen some horribly complex examples on the net), something like this ...
class Animal:
DOG = 1
CAT = 2
x = Animal.DOG
In Python 3.4 (PEP 435), you can make Enum the base class. This gets you a little bit of extra functionality, described in the PEP. For example, enum members are distinct from integers, and they are composed of a name
and a value
.
class Animal(Enum):
DOG = 1
CAT = 2
print(Animal.DOG)
#
print(Animal.DOG.value)
# 1
print(Animal.DOG.name)
# "DOG"
If you don't want to type the values, use the following shortcut:
class Animal(Enum):
DOG, CAT = range(2)
Enum
implementations can be converted to lists and are iterable. The order of its members is the declaration order and has nothing to do with their values. For example:
class Animal(Enum):
DOG = 1
CAT = 2
COW = 0
list(Animal)
# [, , ]
[animal.value for animal in Animal]
# [1, 2, 0]
Animal.CAT in Animal
# True