How to Convert an Enum to an Integer in Python

In this article, we will instruct you to Convert an Enum to an Integer in Python by using the IntEnum class and accessing the enum’s value. If you are looking for how to do that, keep reading. There is a lot of knowledge that surprises you. Let’s move on.

Enum in Python

In Python, an enumeration is a set of symbolic names (members) bound to unique, constant values. These names are also called enumerators. You can use enumerations in Python to define a set of values acceptable for a particular field, like the days of the week.

Here’s an example of how to define an enumeration in Python:

Code:

from enum import IntEnum

class DaysOfTheWeek(IntEnum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

today = DaysOfTheWeek.FRIDAY
print(today)

Result:

DaysOfTheWeek.FRIDAY

We have another article discussing Enum in Python. Please take a visit if you have any confusion. Now, we will show you how to convert an Enum to an Integer.

Convert an Enum to an Integer in Python

Using the value attribute of the Enum member

In Python, you can convert an Enum to an integer by using the value attribute of the Enum member. For example:

Code:

from enum import Enum
 
class DaysOfTheWeek(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

today = DaysOfTheWeek.FRIDAY
print("The value of FRIDAY is:", today.value)

Result:

The value of FRIDAY is: 5

Use the IntEnum class

An IntEnum is a subclass of the Python Enum class that allows you to define Enum members with integer values. The main difference between IntEnum and the regular Enum is that the values of IntEnum members are stored as integers rather than as strings. You can use IntEnum members in arithmetic operations and compare them using the usual comparison operators (<, >, ==, etc.), just like you would with regular integers. Using the IntEnum class, you can easily take the value of the enum member as an integer.

Code:

from enum import IntEnum
 
class DaysOfTheWeek(IntEnum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7
    
today = DaysOfTheWeek.FRIDAY
print("The value of FRIDAY is:", today.value)

Result:

The value of FRIDAY is: 5

Summary

In summary, you can Convert an Enum to an Integer in Python in two following ways: Accessing the value attribute of the enum member or using the IntEnum class instead of the Enum class.

Leave a Reply

Your email address will not be published. Required fields are marked *