On 04/24/2016 08:20 AM, Ian Kelly wrote:
On Sun, Apr 24, 2016 at 1:20 AM, Ethan Furman wrote:

What fun things can Java enums do?

Everything that Python enums can do, plus:
>
--> Planet.EARTH.value
(5.976e+24, 6378140.0)
--> Planet.EARTH.surface_gravity
9.802652743337129

This is incredibly useful, but it has a flaw: the value of each member
of the enum is just the tuple of its arguments. Suppose we added a
value for COUNTER_EARTH describing a hypothetical planet with the same
mass and radius existing on the other side of the sun. [1] Then:

--> Planet.EARTH is Planet.COUNTER_EARTH
True

If using Python 3 and aenum 1.4.1+, you can do

--> class Planet(Enum, settings=NoAlias, init='mass radius'):
...     MERCURY = (3.303e+23, 2.4397e6)
...     VENUS   = (4.869e+24, 6.0518e6)
...     EARTH   = (5.976e+24, 6.37814e6)
...     COUNTER_EARTH = EARTH
...     @property
...     def surface_gravity(self):
...         # universal gravitational constant  (m3 kg-1 s-2)
...         G = 6.67300E-11
...         return G * self.mass / (self.radius * self.radius)
...
--> Planet.EARTH.value
(5.976e+24, 6378140.0)
--> Planet.EARTH.surface_gravity
9.802652743337129
--> Planet.COUNTER_EARTH.value
(5.976e+24, 6378140.0)
--> Planet.COUNTER_EARTH.surface_gravity
9.802652743337129
Planet.EARTH is Planet.COUNTER_EARTH
False


* Speaking of AutoNumber, since Java enums don't have the
instance/value distinction, they effectively do this implicitly, only
without generating a bunch of ints that are entirely irrelevant to
your enum type. With Python enums you have to follow a somewhat arcane
recipe to avoid specifying values, which just generates some values
and then hides them away. And it also breaks the Enum alias feature:

--> class Color(AutoNumber):
...     red = default = ()  # not an alias!
...     blue = ()
...

Another thing you could do here:

--> class Color(Enum, settings=AutoNumber):
...     red
...     default = red
...     blue
...
--> list(Color)
[<Color.red: 1>, <Color.blue: 2>]
--> Color.default is Color.red
True

--
~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to