Convert an Integer to an Enum in Python

avatar

Borislav Hadzhiev

Last updated: Jun 17, 2022

banner

Photo from Unsplash

Convert an Integer to an Enum in Python #

Use parentheses to convert an integer to an enum in Python, e.g. print(Sizes(1)). You can pass the integer value of an enum member as an argument to the class and it will return the enum member.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes(1)) # 👉️ Sizes.SMALL print(Sizes(2)) # 👉️ Sizes.MEDIUM print(Sizes(3)) # 👉️ Sizes.LARGE print(Sizes(1).name) # 👉️ SMALL print(Sizes(1).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 could also extend from the IntEnum class 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(1)) # 👉️ Sizes.SMALL print(Sizes(2)) # 👉️ Sizes.MEDIUM print(Sizes(3)) # 👉️ Sizes.LARGE print(Sizes(1).name) # 👉️ SMALL print(Sizes(1).value) # 👉️ 1 print(Sizes.SMALL == 1) # 👉️ True print(Sizes.MEDIUM == 2) # 👉️ True

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

Here is an example that takes user input and uses it to access an enum member.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 value = input('Pick size - 1, 2 or 3: ') print(value) # 👉️ 2 print(Sizes(int(value))) # 👉️ Sizes.MEDIUM print(Sizes(int(value)).name) # 👉️ MEDIUM print(Sizes(int(value)).value) # 👉️ 2

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.