How To Check If A Value Exists In Python Enum

Check if a value exists in an Enum in Python

To check if a value exists in an Enum in Python, you can use the 'value' and the __member__ attribute. Follow the article to better understand.

Check if a value exists in an Enum in Python

Enum stands for enumeration, which is enumeration in Python. The point of Enum is that it is advantageous when representing data representing a finite set. The Enums class generates the enumeration. An enumeration consists of names and data linked together.

Example:

from enum import Enum

class FootballClubs(Enum):
	ManchesterUnited = 1
	Liverpool = 2
	ManchesterCity = 3
	NottinghamForest = 4

# Printing enum member as a string
print(FootballClubs.ManchesterUnited)

# Use the "name" keyword to print out the name of the enum member
print(FootballClubs.ManchesterUnited.name)

# Use the "name" keyword to print out the value of the enum member
print(FootballClubs.ManchesterUnited.value)

To check if a value exists in an Enum in Python. You can use the following ways:

Use ‘value’ attribute

Example:

  • Import the module named “enum “.
  • The Enums class generates enumerations. In this example, I created an enumeration named ‘FootballClubs’.
  • Using the ‘value’ attribute to get the values in the ‘FootballClubs’ enum
  • Use the in operator to check if a value exists in an Enum.
from enum import Enum

class FootballClubs(Enum):
	ManchesterUnited = 1
	Liverpool = 2
	ManchesterCity = 3
	NottinghamForest = 4

# Using the 'value' attribute to get the values in the 'FootballClubs' enum
valuesClub = [club.value for club in FootballClubs]

# The in operator checks if a value exists in an Enum
print(1 in valuesClub)
print(7 in valuesClub) 

Output:

True
False

The value 1 is in the Enum, so it returns True. The value 7 is not in the Enum, so it returns False.

Use the __member__ attribute

Syntax:

Enum.__member__

Example:

  • Import the module named “enum “.
  • The Enums class generates enumerations. In this example, I created an enumeration named ‘FootballClubs’.
  • Use the in operator with the _member_ attribute to check if a name exists in an Enum.
from enum import Enum

class FootballClubs(Enum):
	ManchesterUnited = 1
	Liverpool = 2
	ManchesterCity = 3
	NottinghamForest = 4

# Using the in operator with the _member_ attribute to check if a value exists in an Enum
print('ManchesterUnited' in FootballClubs.__members__)
print('Liverpool' in FootballClubs.__members__)
print('RealMadrid' in FootballClubs.__members__) 

Output:

True
True
False

Summary

Here are the methods that can help you check if a value exists in an Enum in Python. If you have any questions about this article, leave a comment below. I will answer your questions. Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *