Enum vs OrderedEnum
Ethan Furman
ethan at stoneleaf.us
Tue Aug 6 20:33:16 EDT 2013
On 08/06/2013 04:46 PM, Ian Kelly wrote:
>
> On Aug 6, 2013 5:15 PM, "Ethan Furman" <ethan at stoneleaf.us <mailto:ethan at stoneleaf.us>> wrote:
>>
>> Use the .value attribute instead. You could also substitute self for Environment.
>
> It feels more natural and readable to compare the enum instances rather than their value attributes. If I am ordering
> the values then that seems to imply that the enumeration itself is ordered. So I guess my question is better stated: is
> there a better way to do this that doesn't involve ordered comparisons at all?
If the only time you are using their Ordered nature is inside the class, it's an implementation detail. As such, using
the value seems fine to me.
There are other options:
- using sets, as Rhodri pointed out (extra work is needed, though, because a set would want to turn into an Enum member)
- using AutoNumber instead of Ordered, and specifing the growth factor directly
AutoNumber
----------
class AutoNumber(Enum):
"ignore any arguments, __init__ can have them"
def __new__(cls, *args):
value = len(cls.__members__) + 1
obj = object.__new__(cls)
obj._value_ = value
return obj
class Environment(AutoNumber):
gaia = 2.0
fertile = 1.5
terran = 1.0
jungle = 1.0
ocean = 1.0
arid = 1.0
steppe = 1.0
desert = 1.0
minimal = 1.0
barren = 0.5
tundra = 0.5
dead = 0.5
inferno = 0.5
toxic = 0.5
radiated = 0.5
def __init__(self, growth_factor):
self._growth_factor = growth_factor
@property
def growth_factor(self):
return self._growth_factor
This works because each Enum member gets its own integer value (1 - 15) in __new__, plus a growth factor that is stored
by __init__. Whether you think this is better I have no idea. ;)
--
~Ethan~
More information about the Python-list
mailing list