Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #52095
| Date | 2013-08-06 17:33 -0700 |
|---|---|
| From | Ethan Furman <ethan@stoneleaf.us> |
| Subject | Re: Enum vs OrderedEnum |
| References | <CALwzidm5LSH891oAvK_tzNBY5K-BNS-D970Pa_LLxZXWCb6O9w@mail.gmail.com> <520182F1.2060709@stoneleaf.us> <CALwzidmhKKnDssRd97zRHhDjmwvDRrXVr+5TW4Zfs1iKWFKnOA@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.291.1375835605.1251.python-list@python.org> (permalink) |
On 08/06/2013 04:46 PM, Ian Kelly wrote:
>
> On Aug 6, 2013 5:15 PM, "Ethan Furman" <ethan@stoneleaf.us <mailto:ethan@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~
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Enum vs OrderedEnum Ethan Furman <ethan@stoneleaf.us> - 2013-08-06 17:33 -0700
csiph-web