An enumeration in Python is a user-defined data type that consists of a set of named values. A finite set of values is defined using an enumeration, and these values can be accessed in Python using their names rather than integer values. Enumerations make code more readable and maintainable, and they also enhance type safety. In this article, we will learn how to find an enumeration by its string value in Python.
To find an enumeration by a string value, we need to follow these steps:
Import the enumeration module in the code
Define an enumeration with the desired set of values
Create a function that takes an enumeration string as input and returns the corresponding enumeration value.
from enum import Enum class ClassName(Enum): Key_1= Value_1 Key_2= Value_2 Key_3= Value_3
Using enumerations in Python requires importing the enumeration and then creating a class that will take the enumeration value as input and also contain the key-value pair for each enumeration value.
In addition to looking up values by name, Enum can also improve code readability.
The code below consists of a function called process_color() that accepts an integer as input and returns a message indicating the color being processed. The code below is not considered a good readable code because we have to remember which color each integer value represents. We can use enumerations to improve code readability.
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 enumerations, we can define an enumeration called color whose values are the same as in the above code. Then by creating a simple function called process_color that takes an integer as input and uses an enum to convert the integer into a named color value. If the input is not a valid color, raise a ValueError with a detailed error message. This makes the code more readable because we now don't have to remember the integer value 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")
In this article, we learned how to find enumeration values using named strings. Enumerations can make code more readable and improve code maintainability. You should consider using enumerations in any project involving a limited set of named values.
The above is the detailed content of Python program to find enum by string value. For more information, please follow other related articles on the PHP Chinese website!