What's the common practice for enums in Python? [duplicate]
class Materials:
Shaded, Shiny, Transparent, Matte = range(4)
>>> print Materials.Matte
3
I've seen this pattern several times:
>>> class Enumeration(object):
def __init__(self, names): # or *names, with no .split()
for number, name in enumerate(names.split()):
setattr(self, name, number)
>>> foo = Enumeration("bar baz quux")
>>> foo.quux
2
You can also just use class members, though you'll have to supply your own numbering:
>>> class Foo(object):
bar = 0
baz = 1
quux = 2
>>> Foo.quux
2
If you're looking for something more robust (sparse values, enum-specific exception, etc.), try this recipe.
I have no idea why Enums are not support natively by Python. The best way I've found to emulate them is by overridding _ str _ and _ eq _ so you can compare them and when you use print() you get the string instead of the numerical value.
class enumSeason():
Spring = 0
Summer = 1
Fall = 2
Winter = 3
def __init__(self, Type):
self.value = Type
def __str__(self):
if self.value == enumSeason.Spring:
return 'Spring'
if self.value == enumSeason.Summer:
return 'Summer'
if self.value == enumSeason.Fall:
return 'Fall'
if self.value == enumSeason.Winter:
return 'Winter'
def __eq__(self,y):
return self.value==y.value
Usage:
>>> s = enumSeason(enumSeason.Spring)
>>> print(s)
Spring
You could probably use an inheritance structure although the more I played with this the dirtier I felt.
class AnimalEnum:
@classmethod
def verify(cls, other):
return issubclass(other.__class__, cls)
class Dog(AnimalEnum):
pass
def do_something(thing_that_should_be_an_enum):
if not AnimalEnum.verify(thing_that_should_be_an_enum):
raise OhGodWhy