Python Program to Lookup enum by String value


Enum in Python is a user-defined data type consisting of a set of named values. A finite set values of is defined using enums and these values can be accessed in Python using their names instead of their integer values. Enum makes the code more readable, and more maintainable and also enforces type safety. In this article, we will see how we can look up enums by their string value in Python.

To look up an enum by string value we need to follow the following steps:

  • Import enum module in the code

  • Define enum with desired set of values

  • Create a function that takes an enum string as input and returns the corresponding enum value.

Syntax

from enum import Enum

class ClassName(Enum):
   Key_1= Value_1
   Key_2= Value_2
   Key_3= Value_3

For using an enum in Python we need to import an enum and then create a class that will take the enum value as input and also contains the key-value pair for every enum value.

Using Enum to Improve Code Readability

Apart from looking up values by their names, Enum can also improve the readability of our code.

Example

The below code consists of a function named process_color() which takes an integer as input and returns the message indicating the color that is being processed. The below code is not considered a good readable code as we have to remember which color each integer value represents. We can improve the readability of code using an enum.

def process_color1(color):
   if color == 1:
      print("Processing red color")
   elif color == 2:
      print("Processing green color")
   elif color == 3:
      print("Processing blue color")
   else:
      raise ValueError(f"{color} is not a valid color")

Using an enum we can define an enum named color with the same set of values as in the above code. Then by creating a simple function called process_color that takes an integer as input and uses the enum to convert the integer to a named color value. If the input is not a valid color then it raises a ValueError with a detailed error message. This makes the code more readable as we now do not have to remember the integer values for each color.

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

def process_color(color):
   try:
      color = Color(color)
   except ValueError:
      raise ValueError(f"{color} is not a valid color")
   print(f"Processing {color.name.lower()} color")

Conclusion

In this article, we understood how to look up enum values using their named string. Enum can make the code more readable and improve code maintainability. Enum should be considered for use in any project which involves a finite set of named values.

Updated on: 17-Apr-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements