Enum vs OrderedEnum

I

Ian Kelly

Using the OrderedEnum recipe from the Python 3.4 docs, I have the
following code:


class Environment(OrderedEnum):

gaia = 1
fertile = 2
terran, jungle, ocean, arid, steppe, desert, minimal = range(3, 10)
barren, tundra, dead, inferno, toxic, radiated = range(10, 16)

def is_standard(self):
return Environment.terran <= self <= Environment.minimal

def is_hostile(self):
return Environment.barren <= self

@property
def growth_factor(self):
if self.is_standard():
return 1.0
elif self.is_hostile():
return 0.5
elif self is Environment.fertile:
return 1.5
elif self is Environment.gaia:
return 2.0
else:
raise AttributeError("Unknown growth_factor for %s" % self)


This works, and the ordering is logical and intuitive, and I think
result is quite readable. That said, really the only reason for
subclassing OrderedEnum instead of Enum is to support the is_standard
and is_hostile methods. In normal usage there is no reason for the
members to be ordered. Can anyone suggest an alternative formulation
that is as readable as the above without relying on OrderedEnum?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,119
Latest member
IrmaNorcro
Top