Python

Python String to Enum Conversion

Converting String to Enum in Python improves the code readability as Enum offers a consistent way for specifying a set of related values. This conversion also makes the code easier to maintain. It also assists in avoiding errors or typos. More specifically, the Enumerated constant values are defined at compile time but cannot be changed during execution.

This blog will discuss the following approaches:

Method 1: String to Enum Conversion in Python Using “getattr()” Function

In Python, “getattr()” is a built-in Python function that fetches the value of an object attribute. This function accepts two arguments. The first argument represents the selected object, and the second one refers to the attribute whose value you want to get. More specifically, this function can also convert a string to Enum.

Syntax

getattr(Object, attr_name)

Here, the “getattr()” function retrieves the value of the specified attribute “attr_name” of the relevant “Object”.

Example

Now, let’s check out the method for converting a string to Enum using the “getattr()” function. To do so, first import the “enum” module from the Enum class:

from enum import Enum

Then, define an Enum class named “Fruit”, add the enumerated constants, and specify the corresponding integer values:

class Fruit(Enum):
    Apple = 3
    Mango = 6
    Orange = 9

Create a string and store the enumerated constant name in it:

fruit_str = 'Apple'

Invoke the “getattr()” function and pass the “Fruit” Enum object and the newly created as the attribute name:

fruit_enum = getattr(Fruit, fruit_str)

Print the resultant value on the console:

print(fruit_enum)

It can be observed from the output that the “Fruit.Apple” is an enumerated constant:

However, an “AttributeError” exception will get triggered in case of passing the attribute name that is not justified as the Enum constant value:

fruit_str = 'Peach'

To handle the mentioned exception, add the try-except block as follows:

try:
   fruit_enum = getattr(Fruit, fruit_str)
   print(fruit_enum)
except AttributeError:
   print(f'Error: {fruit_str} is not in the list')

Add the code block with “try” that needs to be executed when the Enum constant has been found. For the other case, specify the respective statements in the “except” block:

Method 2: String to Enum Conversion in Python Using “__members__” Attribute

The Enum Python class offers an attribute named “__members__” that is automatically created. This attribute is more like a dictionary that maps the enumerated member to the corresponding values.

Syntax

Object.__members__[attr_name]

Here, the “__members__ ” attribute gets the value of the specified attribute “attr_name” of the specified Enum “Object”.

Example

To use the “__members__” attribute for a string to Enum conversion, firstly, create a string whose value is the same as the required Enum constant:

fruit_str = 'Mango'

Then, specify the following code in the try-except block of your code:

try:
 fruit_enum = Fruit.__members__[fruit_str]
 print(fruit_enum)
except AttributeError:
   print(f'Error: {fruit_str} is not in the list')

The first statement added in the try block tries to access the “fruit_str” member of the Fruit Enum class with the “__members__” attribute. If the specified string gets matched with any of the Enum constants, the corresponding value will be printed out. However, in the other case, the “except” block displays the defined message:

Method 3: String to Enum Conversion in Python Using Enum Class Method

Enum class also provides a method for converting a string to Enum in Python. To utilize it, check out the stated syntax.

Syntax

Enum.<EnumClassName>.<member_name>.

Example

Specify the required Enum constant value in a string:

fruit_str = 6

Then, pass the created string using the Enum class method Fruit() and print the output on the console:

try:
  fruit_enum = Fruit(fruit_str)
  print(fruit_enum)
except AttributeError:
  print(f'Error: {fruit_str} is not in the list')

It can be observed that the enumerated member name has been fetched.

Conclusion

To convert the string to Enum in Python, the “getattr()” function, “__members__” attribute, or the Enum class method are used. All of these approaches fetch the enumerated constant of the specified class. Moreover, in combination with the stated approaches, the try-except also assists in achieving the desired functionality. This post covered different methods for the string to Enum conversion in Python.

About the author

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor's degree in computer science.