Check if a name exists in an Enum in Python

avatar

Borislav Hadzhiev

Last updated: Jun 17, 2022

banner

Photo from Unsplash

Check if a name exists in an Enum in Python #

To check if a name exists in an enum in Python:

  1. Use a list comprehension to get a list of all of the enum's names.
  2. Use the in operator to check if the name is present in the list.
  3. The in operator will return True if the name is in the list.
main.py
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 'SMALL' in names: # 👇️ this runs print('SMALL is in enum names')

We used a list comprehension to get a list of the enum's names.

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

The last step is to use the in operator to check if a specific name is in the list.

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.

Alternatively, you could use the __members__ attribute on the class.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 # 👇️ {'SMALL': <Sizes.SMALL: 1>, 'MEDIUM': <Sizes.MEDIUM: 2>, 'LARGE': <Sizes.LARGE: 3>} print(Sizes.__members__) if 'SMALL' in Sizes.__members__: # 👇️ this runs print('SMALL is in enum names')

The __members__ attribute is an ordered mapping of names to members.

It contains all names defined in the enum (including the aliases).

If you need to check if a specific value is present in an enum, use a list comprehension.

main.py
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 3 in values: # 👇️ this runs print('3 is in enum values')

Instead of accessing the name attribute, we used the value attribute to get a list of the enum's values.

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.