Enumerations are a way to group constants together and improve code readibility and type checking. Here is an example of an enumeration in Python.
from enum import Enum from random import randint class Color(Enum): RED = 1 BLUE = 2 GREEN = 3 def pick_color(): pick = randint(1, 3) if pick == Color.RED.value: return Color.RED elif pick == Color.BLUE.value: return Color.BLUE elif pick == Color.GREEN.value: return Color.GREEN def print_color(color): if color == Color.RED: print('Red') elif color == Color.GREEN: print('Green') elif color == Color.BLUE: print('Blue') if __name__ == '__main__': color = pick_color() print_color(color)
Python enumeration extend the enum class. After inheriting from enum, we just list out the values in our enumeration and assign them constants.
The pick_color() function returns a randomly picked enumeration. We then pass that value to print_color().
You’ll notice that print_color accepts a color object and does comparisons against the values of the Color enumeration. You can see that the code is much more readible (and also more robust) than using literals such as 1, 2, or 3 in our code. The other nice aspect of using an enumeration is that we can change the values of our constants without breaking code and we can add more constants if needed.
One thought on “Enumerations—Python”