Skip to main content

How to Convert Python Enums to Integers in and Viceversa

In Python, you may want to work with enums that have integer values.

This guide explains how to convert between enums and integers, using both IntEnum for integer-based enums and standard enums.

How to Convert an Integer to an Enum in Python

This section explains how to work with enums that have integer values in Python, covering how to access integer values, use IntEnum, and convert between enums and integers.

Using IntEnum

For enums where the members are integers, use IntEnum:

from enum import IntEnum, auto

class Sizes(IntEnum):
SMALL = 1
MEDIUM = 2
LARGE = 3

print(Sizes(1)) # Output: Sizes.SMALL
print(Sizes.SMALL.name) # Output: SMALL
print(Sizes.SMALL.value) # Output: 1
print(Sizes.SMALL == 1) # Output: True
  • IntEnum: Members of an IntEnum are integers, so you can compare them directly to integers.
  • Sizes(1): You can look up an enum member by its integer value.

Using auto() for Automatic Values

The auto() function (from enum) can automatically assign sequential integer values:

from enum import IntEnum, auto

class Sizes(IntEnum):
SMALL = auto() # Value will be 1
MEDIUM = auto() # Value will be 2
LARGE = auto() # Value will be 3

print(list(Sizes))
# Output: [<Sizes.SMALL: 1>, <Sizes.MEDIUM: 2>, <Sizes.LARGE: 3>]

print(Sizes.SMALL.name) # Output: SMALL
print(Sizes.SMALL.value) # Output: 1

  • auto(): Automatically assigns a unique value, starting from 1. This is very convenient when the specific integer values don't matter.

Using regular Enum

If you do not want your enum to be automatically castable to integers, you can use the regular Enum approach:

from enum import Enum

class Sizes(Enum):
SMALL = 1
MEDIUM = 2
LARGE = 3
  • In this case, you can still access the integer values with the value property, but you will not be able to compare it to integers.

Converting an Integer to an Enum in Python

This section explains how to convert an integer back into its corresponding enum member in Python. This is the reverse of getting the integer value of an enum.

Direct Conversion using Enum Class

You can directly convert an integer to its corresponding enum member by calling the enum class with the integer value:

from enum import Enum

class Sizes(Enum):
SMALL = 1
MEDIUM = 2
LARGE = 3

print(Sizes(1)) # Output: Sizes.SMALL
print(Sizes(1).name) # Output: SMALL
print(Sizes(1).value) # Output: 1
  • Sizes(1): This directly looks up the enum member with the value 1. This is the most straightforward way.

Handling Invalid Integers

If you pass an integer that doesn't correspond to any enum member's value, a ValueError will be raised:

print(Sizes(99))   # Raises ValueError

To prevent the program from crashing, you should add a try/except block to catch this error.