Borislav Hadzhiev
Last updated: Jun 17, 2022
Check out my new book
Use the name
attribute on the enum member to get the name, e.g.
Sizes.SMALL.name
. If you only have the corresponding value, pass the value to
the enumeration class and access the name
attribute.
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes.SMALL.name) # 👉️ SMALL # 👇️ access enum name by value print(Sizes(1).name) # 👉️ SMALL print(Sizes['SMALL'].name) # 👉️ SMALL
name
and value
properties on an enum member to get the enum's name and value.from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes.MEDIUM.name) # 👉️ MEDIUM print(Sizes.MEDIUM.value) # 👉️ 2
You can also use square brackets to access enum members.
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 name = 'LARGE' print(Sizes[name].name) # 👉️ MEDIUM print(Sizes[name].value) # 👉️ 2
If you only have the value that corresponds to the enum member, pass it to the
enumeration class and 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
You can use a list comprehension if you need to get the list of all of the names in the enum.
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 names = [member.name for member in Sizes] print(names) # 👉️ ['SMALL', 'MEDIUM', 'LARGE'] values = [member.value for member in Sizes] print(values) # 👉️ [1, 2, 3]
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 in
operator if you need to check if a specific name or a
specific value exists in an enum.
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 names = [member.name for member in Sizes] print(names) # 👉️ ['SMALL', 'MEDIUM', 'LARGE'] if 'MEDIUM' in names: # 👇️ this runs print('MEDIUM is in enum')
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)