HomeLinuxPython String to Enum Conversion

Python String to Enum Conversion


Changing String to Enum in Python improves the code readability as Enum presents a constant manner for specifying a set of associated values. This conversion additionally makes the code simpler to take care of. It additionally assists in avoiding errors or typos. Extra particularly, the Enumerated fixed values are outlined at compile time however can’t be modified throughout execution.

This weblog will focus on the next approaches:

Methodology 1: String to Enum Conversion in Python Utilizing “getattr()” Operate

In Python, “getattr()” is a built-in Python operate that fetches the worth of an object attribute. This operate accepts two arguments. The primary argument represents the chosen object, and the second refers back to the attribute whose worth you need to get. Extra particularly, this operate also can convert a string to Enum.

Syntax

getattr(Object, attr_name)

Right here, the “getattr()” operate retrieves the worth of the required attribute “attr_name” of the related “Object”.

Instance

Now, let’s try the tactic for changing a string to Enum utilizing the “getattr()” operate. To take action, first import the “enum” module from the Enum class:

Then, outline 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 retailer the enumerated fixed identify in it:

Invoke the “getattr()” operate and go the “Fruit” Enum object and the newly created because the attribute identify:

fruit_enum = getattr(Fruit, fruit_str)

Print the resultant worth on the console:

It may be noticed from the output that the “Fruit.Apple” is an enumerated fixed:

Nevertheless, an “AttributeError” exception will get triggered in case of passing the attribute identify that’s not justified because the Enum fixed worth:

To deal with the talked about exception, add the try-except block as follows:

attempt:
   fruit_enum = getattr(Fruit, fruit_str)
   print(fruit_enum)
besides AttributeError:
   print(f‘Error: {fruit_str} is just not within the listing’)

Add the code block with “attempt” that must be executed when the Enum fixed has been discovered. For the opposite case, specify the respective statements within the “besides” block:

Methodology 2: String to Enum Conversion in Python Utilizing “__members__” Attribute

The Enum Python class presents an attribute named “__members__” that’s mechanically created. This attribute is extra like a dictionary that maps the enumerated member to the corresponding values.

Syntax

Object.__members__[attr_name]

Right here, the “__members__ ” attribute will get the worth of the required attribute “attr_name” of the required Enum “Object”.

Instance

To make use of the “__members__” attribute for a string to Enum conversion, firstly, create a string whose worth is similar because the required Enum fixed:

Then, specify the next code within the try-except block of your code:

attempt:
 fruit_enum = Fruit.__members__[fruit_str]
 print(fruit_enum)
besides AttributeError:
   print(f‘Error: {fruit_str} is just not within the listing’)

The primary assertion added within the attempt block tries to entry the “fruit_str” member of the Fruit Enum class with the “__members__” attribute. If the required string will get matched with any of the Enum constants, the corresponding worth can be printed out. Nevertheless, within the different case, the “besides” block shows the outlined message:

Methodology 3: String to Enum Conversion in Python Utilizing Enum Class Methodology

Enum class additionally supplies a technique for changing a string to Enum in Python. To put it to use, try the acknowledged syntax.

Syntax

Enum.<EnumClassName>.<member_name>.

Instance

Specify the required Enum fixed worth in a string:

Then, go the created string utilizing the Enum class technique Fruit() and print the output on the console:

attempt:
  fruit_enum = Fruit(fruit_str)
  print(fruit_enum)
besides AttributeError:
  print(f‘Error: {fruit_str} is just not within the listing’)

It may be noticed that the enumerated member identify has been fetched.

Conclusion

To transform the string to Enum in Python, the “getattr()” operate, “__members__” attribute, or the Enum class technique are used. All of those approaches fetch the enumerated fixed of the required class. Furthermore, together with the acknowledged approaches, the try-except additionally assists in attaining the specified performance. This submit lined totally different strategies for the string to Enum conversion in Python.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments