Enum class in Python

What is an Enum?

In Python, an enumeration is a set of named values that address a finite set of conceivable outcomes. For example, assuming that we were composing a program that expected to address the days of the week, we could characterize an enumeration with seven named values: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, and Sunday.

An enumeration permits you to work with these values in a more significant manner than basically utilizing strings or integers. For example, you could analyse two days of the week utilizing the == operator, and it would function true to form:

Characteristics of enum:

  • The users can check the types of Enum by using the type()
  • By using the 'name' keyword, the users can display the name of the Enum.
  • The Enum is the evaluable string representation of the object known as repr().

Example: Enum class for creating enumerations

Output:

The member of Enum class as the string is : Weekdays.Monday
The member of Enum class as a repr is : 
The type of the member of Enum class is : 
The name of the member of Enum class is : Friday

Example 2: How to print Enum as an Iterable list

The users can print the Enum class as an iterable list.

In the following example, we will use for loop to print all the members of the Enum class.

Code

Output:

The member of Enum class are : 
Weekdays.Sunday
Weekdays.Monday
Weekdays.Tuesday
Weekdays.Wednesday
Weekdays.Thursday
Weekdays.Friday
Weekdays.Saturday

Example 3: How to Hash Enum Class

The members of the Enum class are called Enumeration, and also hashable. Therefore, these members can be used for sets and dictionaries.

Code

Output:

Enum class is hashed

Example 4: How to access Enum members

The users can access the members of the Enum class by using the value or the name of the member items. The name of the Enum is used as an index.

Code

Output:

The member of Enum class accessed by name: 
Days.Monday
The member of Enum class accessed by name: 
Days.Friday
The member of Enum class accessed by Value: 
Days.Sunday
The member of Enum class accessed by Value: 
Days.Thursday

Example 5: How to Compare the Enums

To compare the Enums, We use the following methods:

  1. Using the "==" and "!=" Operator
  2. Using the "is" Operator
  3. Using the "in" Operator

Code

Output:

Match
Do not Match
Match
Do not Match

Conclusion

In this article, we've explored the enum class in Python, which permits us to characterize and work with enumerations in our code. By utilizing an enumeration, we can make your code more coherent and less mistake inclined, while likewise giving extra sort security.






Latest Courses