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?
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?