Borislav Hadzhiev
Last updated: Jun 17, 2022
Photo from Unsplash
To get an enum name by value, pass the value to the enumeration class and
access the name
attribute, e.g. Sizes(1).name
. When the value is passed to
the class, we get access to corresponding enum member, on which we can access
the name
attribute.
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes(1).name) # 👉️ SMALL print(Sizes(2).name) # 👉️ MEDIUM print(Sizes(3).name) # 👉️ LARGE
The Sizes(1)
syntax allows us to pass an integer to the class and get the
corresponding enum member.
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 value = 1 print(Sizes(value)) # 👉️ Sizes.SMALL print(Sizes(value).name) # 👉️ SMALL
If you need to get a list of an enum's names or values use a list comprehension.
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 values = [member.value for member in Sizes] print(values) # 👉️ [1, 2, 3] names = [member.name for member in Sizes] print(names) # 👉️ ['SMALL', 'MEDIUM', 'LARGE']
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.
You can use the same approach if you need to get a list of tuples containing the name and value of each enum member.
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 result = [(member.name, member.value) for member in Sizes] # 👇️ [('SMALL', 1), ('MEDIUM', 2), ('LARGE', 3)] print(result)
The first element in each tuple is the name, and the second - the value of the enum member.
Use the in
operator if you need to check if a value is in an enum.
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 values = [member.value for member in Sizes] print(values) # 👉️ [1, 2, 3] if 2 in values: # 👇️ this runs print('2 is in values')
The
in operator
tests for membership. For example, x in l
evaluates to True
if x
is a
member of l
, otherwise it evaluates to False
.
You can use a simple for
loop if you need to iterate over an enum.
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 for size in Sizes: print(size) print(size.name, size.value)