Convert an Enum to an Integer in Python

avatar

Borislav Hadzhiev

Fri Jun 17 20222 min read

Convert an Enum to an Integer in Python #

Use the IntEnum class from the enum module to convert an enum to an integer in Python. You can use the auto() class if the exact value is unimportant. To get a value of an enum member, use the value attribute on the member.

main.py
from enum import IntEnum class Sizes(IntEnum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes(1)) # 👉️ Sizes.SMALL print(Sizes.SMALL.name) # 👉️ SMALL print(Sizes.SMALL.value) # 👉️ 1

The Sizes(1) syntax allows us to pass an integer to the class and get the corresponding enum member.

This is useful when you don't know the name of the enum member ahead of time (because it's read from a file or fetched from an API).

You can also use the auto() class if the exact value of the enum members is unimportant.

main.py
from enum import IntEnum, auto class Sizes(IntEnum): SMALL = auto() MEDIUM = auto() LARGE = auto() # 👇️ [<Sizes.SMALL: 1>, <Sizes.MEDIUM: 2>, <Sizes.LARGE: 3>] print(list(Sizes)) print(Sizes.SMALL.name) # 👉️ SMALL print(Sizes.SMALL.value) # 👉️ 1

By default, the initial value when using the auto class starts at 1.

Extending from the IntEnum class is useful if you have to compare members of the enum to integers.

main.py
from enum import IntEnum class Sizes(IntEnum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes.SMALL == 1) # 👉️ True print(Sizes.MEDIUM == 2) # 👉️ True

Alternatively, you can use the more generic Enum class from the enum module.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes(1)) # 👉️ Sizes.SMALL print(Sizes.SMALL.name) # 👉️ SMALL print(Sizes.SMALL.value) # 👉️ 1

You can also use square brackets to programmatically access enum members.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 name = 'MEDIUM' print(Sizes[name].value) # 👉️ 2 print(Sizes['SMALL'].value) # 👉️ 1

You can use a simple for loop if you need to iterate over an enum.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 for size in Sizes: print(size) print(size.name, size.value)

You can use a list comprehension to check if a specific value is in an enum.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 # 👇️ check enum member type print(type(Sizes.MEDIUM)) # 👉️ <enum 'Sizes'> # 👇️ check if member belongs to Enum print(isinstance(Sizes.MEDIUM, Sizes)) # 👉️ True values = [member.value for member in Sizes] print(values) # 👉️ [1, 2, 3] if 2 in values: # 👇️ this runs print('2 is in values')

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

Use the search field on my Home Page to filter through my more than 1,000 articles.