Home > OS >  Can I use an Enum with floating point values and comparators in Python 3.9 and still leverage the ef
Can I use an Enum with floating point values and comparators in Python 3.9 and still leverage the ef

Time:10-26

For a Python 3.9 project, we would like to use Enums because we have binning on a number of properties as per the example below. Unfortunately, these bins correspond to real numbers and will be used in large formulae, so IntEnum probably isn't much of an option.

For example:

from enum import Enum

class WaterVapor(Enum):
    VERY_DRY = 0.2
    DRY = 0.5
    MEDIAN = 0.8
    WET = 1.0

If I were to, say, implement a ComparableEnum that implements the necessary comparison operators and simply compares the values of two ComparableEnums, and I populated a numpy array of these, would I still get the performance benefits of numpy when doing operations on this array? My intuition tells me no, but I haven't found a definitive answer yet.

Any alternative design recommendations if my intuition is correct would also be very much appreciated. Using floating point numbers is essential to the computations that we will be doing, and so are the performance enhancements offered by numpy. Limiting them to specific values would be really nice to have, but not at the expense of the other two factors.

CodePudding user response:

You need to inherit from float:

from enum import Enum

class WaterVapor(float, Enum):
    VERY_DRY = 0.2
    DRY = 0.5
    MEDIAN = 0.8
    WET = 1.0

print(WaterVapor.VERY_DRY.value)
  • Related