Python Enum Get Value – Five Best Methods

4/5 - (1 vote)

This article delves into the diverse methods of extracting values from Python’s Enum class. The Enum class in Python offers a platform to define named constants, known as enumerations.

These enumerations can be accessed through various techniques:

  1. By Name/Key: Access the enumeration directly through its designated name or key.
  2. By String/String Name: Utilize a string representation of the enumeration’s name, often in conjunction with the getattr function.
  3. By Index: Retrieve the enumeration based on its sequential order within the Enum class.
  4. By Variable: Leverage a variable containing the enumeration’s name, typically paired with the getattr function.
  5. By Default: Obtain the initial or default value of the enumeration, essentially the foremost member defined in the Enum class.

This article underscores the adaptability and multifaceted nature of the Enum class in Python, illustrating the myriad ways one can access the values of its constituents.

Method 1: Python Enum Get Value by Name

Problem Formulation: How can you retrieve the value of an Enum member in Python using its name or key?

In Python, the Enum class allows you to define named enumerations. To get the value of an Enum member using its name (=key), you can directly access it as an attribute of the Enum class.

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
print(Color.RED.value)
# 1

Method 2: Python Enum Get Value by String/String Name

Problem Formulation: How can you retrieve the value of an Enum member in Python using a string representation of its name?

You can use the string representation of an Enum member’s name to access its value by employing the getattr() function.

color_name = "RED"
print(getattr(Color, color_name).value)

Method 3: Python Enum Get Value by Index

Problem Formulation: How can you retrieve the value of an Enum member in Python using its index?

Enum members can be accessed by their order using the list() conversion. The index refers to the order in which members are defined.

print(list(Color)[0].value)
# 1

Method 4: Python Enum Get Value by Variable

Problem Formulation: How can you retrieve the value of an Enum member in Python using a variable that represents its name?

Similar to accessing by string, you can use the getattr() function with a variable holding the Enum member’s name.

var_name = "GREEN"
print(getattr(Color, var_name).value)
# 2

Method 5: Python Enum Get Value by Default

Problem Formulation: How can you retrieve the default value (or the first value) of an Enum in Python?

By converting the Enum to a list and accessing the first element, you can retrieve the default or first value of the Enum.

print(list(Color)[0].value)
# 1

๐Ÿ’ก Recommended: Robotaxi Tycoon โ€“ Scale Your Fleet to $1M! A Python Mini Game Made By ChatGPT