How to get Enum values in Python

avatar

Borislav Hadzhiev

Last updated: Jun 17, 2022

banner

Check out my new book

Get Enum values in Python #

To get a value in an enum in Python:

  1. Use dot notation to access the specific enum member, e.g. Color.GREEN.
  2. Access the value attribute on the enum member, e.g. Color.GREEN.value.
main.py
from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' print(Color.GREEN.value) # 👉️ 'go' print(Color['GREEN'].value) # 👉️ 'go' print(Color.RED.value) # 👉️ 'stop' print(Color['RED'].value) # 👉️ 'stop'
You can use the name and value properties on an enum member to get the enum's name and value.
main.py
from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' print(Color.GREEN.value) # 👉️ 'go' print(Color.GREEN.name) # 👉️ 'GREEN'

You can also use square brackets to access enum members.

main.py
from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' name = 'GREEN' print(Color[name].value) # 👉️ 'go' print(Color['GREEN'].value) # 👉️ 'go'
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 use a list comprehension to check if a specific value is in an enum.

main.py
from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' values = [member.value for member in Color] print(values) # 👉️ ['stop', 'go', 'get ready'] if 'go' in values: # 👇️ this runs print('go is in values')

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

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.

main.py
from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' for color in Color: print(color) print(color.name, color.value)
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.