Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement an increment function for enum objects? [duplicate]

Tags:

python

enums

I'm working with a Dyson fan and am trying to write a function that increases the speed of the fan. The enum object FanSpeed has the following members. When I execute [print(i) for i in FanSpeed] I get:

FanSpeed.FAN_SPEED_1
FanSpeed.FAN_SPEED_2
FanSpeed.FAN_SPEED_3
FanSpeed.FAN_SPEED_4
FanSpeed.FAN_SPEED_5
FanSpeed.FAN_SPEED_6
FanSpeed.FAN_SPEED_7
FanSpeed.FAN_SPEED_8
FanSpeed.FAN_SPEED_9
FanSpeed.FAN_SPEED_10

So the first enum object (above) has the name FAN_SPEED_1 (FanSpeed.FAN_SPEED_1.name) and has a value of "0001" (FanSpeed.FAN_SPEED_1.value), and so on.

The function to set speed (to 5 in this example is):

fan.set_configuration(fan_mode=FanMode.FAN, fan_speed=FanSpeed.FAN_SPEED_5)

I can't figure out how to write a function that gets the current speed and then sets it to one level higher. I've tried:

1/ Treating the enum object as a a string and replacing the last character with a number (character type) that's higher. This approach doesn't work for enum objects though.

2/ Looking for some kind of increment or next function but those don't seem to exist for enum objects.

like image 218
megashigger Avatar asked Jul 25 '17 06:07

megashigger


1 Answers

So let's use the example from Python documentation:

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

current_color = Color.RED
new_color = Color(current_color.value + 1)
>>> new_color == Color.GREEN
True

Thanks, I've yet to play with the Enum type, so this was a good learning experience.

If you want to do this for non-int values you could do the following:

class Color(Enum):
    red = "0001"
    blue = "0002"


def get_next_color(current_color):
    current_color_idx = list(Color).index(current_color)
    next_color_idx = (current_color_idx + 1) % len(Color)
    next_color = list(Color)[next_color_idx]
    return next_color
like image 126
Cory Madden Avatar answered Sep 20 '22 16:09

Cory Madden