How to compare a string with an Enum in Python

avatar

Borislav Hadzhiev

Last updated: Jun 18, 2022

banner

Photo from Unsplash

Compare a string with an Enum in Python #

To compare a string with an enum, extend from the str class when declaring your enumeration class, e.g. class Color(str, Enum):. You will then be able to compare a string to an enum member using the equality operator ==.

main.py
from enum import Enum class Color(str, Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' my_str = 'go' if my_str == Color.GREEN: # 👇️ this runs print('success') print(my_str == Color.YELLOW) # 👉️ False

The Color class is a subclass of both str and Enum which makes comparing strings to enum members possible.

Note that there are some rules when working with derived enumerations:

  1. When subclassing Enum, specify mix-in types before the Enum class.
  2. While Enum can have members of any type, once additional types are mixed, all the members in the enum must have values of the specified type (e.g. str).

Alternatively, you can use the value attribute on the enum member and compare the value to a string.

main.py
from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' my_str = 'go' if my_str == Color.GREEN.value: # 👇️ this runs print('success') print(my_str == Color.YELLOW.value) # 👉️ False

We used the value attribute on members of the enum to get string values that we can safely compare.

main.py
from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' print(Color.RED.value) # 👉️ 'stop' print(Color.GREEN.value) # 👉️ 'go' print(Color.YELLOW.value) # 👉️ 'get ready'

You can also use square brackets to access the enum member if you don't know its name ahead of time.

main.py
from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' name_1 = 'RED' print(Color[name_1].value == 'stop') # 👉️ True

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).

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.