Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52095 > unrolled thread

Re: Enum vs OrderedEnum

Started byEthan Furman <ethan@stoneleaf.us>
First post2013-08-06 17:33 -0700
Last post2013-08-06 17:33 -0700
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Enum vs OrderedEnum Ethan Furman <ethan@stoneleaf.us> - 2013-08-06 17:33 -0700

#52095 — Re: Enum vs OrderedEnum

FromEthan Furman <ethan@stoneleaf.us>
Date2013-08-06 17:33 -0700
SubjectRe: Enum vs OrderedEnum
Message-ID<mailman.291.1375835605.1251.python-list@python.org>
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~

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web