Python Enum

Enum is a python class which is used to create enumerations. These are a set of unique and non-variable values which are denoted using symbols. The elements of enumeration can be symbolic names or enumerations itself.

What is Python Enum

Python enum can be implemented using "enum "which is actually a module name. Python enum can be created by the user using classes. They have names as well as associated values in python. The main purpose of using enums in python is to make the code readable.

Below is a list of a few characteristics of Enum in python:

  • Method type() can be used by the user to check the type of enum class.
  • The name of the enum class can be displayed using the 'name' keyword.
  • The Enum is a type of string representation which can be evaluated with the object known as repr() or even a string. 
  • Python enums are iterable, and iterations are performed using loops.
  • Enum in python can perform hashing, meaning they can be used with python sets or dictionaries.

Become a Python Certified professional by learning this HKR Python Training!

Importing Enum module 

Enum is a python class which is used to create enumerations. It can be imported using 'import' at the top of the python code, which imports all the necessary enum methods.

Below is a basic python code to understand the name, type and repr() of enumerations in python. This will be done using importing Enum in python

import enum

class fruit(enum.Enum):

apple = 1

banana = 2

cherry = 3


print ("The enum member will be represented as : ",end="")

print (fruit.apple)


print ("The repr will be represented as : ",end="")

print (repr(fruit.apple))


print ("The type will represented as: ",end ="")

print (type(fruit.apple))


print ("The name will be represented as: ",end ="")

print (fruit.apple.name)
Output:
The enum member will be represented as fruit.apple

The repr will be represented as:

The type will be represented as: <enum 'fruit'>

The name will be represented as apple

Printing enum as an iterable

The user can print enum in the form of an iterable list.

We can see the demonstration of enum as an iterable in the python code below:

import enum  

class fruits(enum.Enum):  

   apple = 1  

   banana = 2  

   cherry = 3  

   kiwi = 4  

   pear = 5  

   watermelon = 6  

   grapes = 7  

print (" The enum member of the class will be : ")  

for fruit in (fruits):  

   print(fruit)
Output:

The enum member of the class will be : 

fruits.apple

fruits.banana

fruits.cherry

fruits.kiwi

fruits.pear

fruits.watermelon

fruits.grapes

>

Enum Hashing

Enum in python can perform hashing, meaning they can be used with python sets or dictionaries.

Below is a basic python code to demonstrate hashing using python enum:

import enum

class fruit(enum.Enum):

apple = 1

banana = 2

cherry = 3


print ("All the enum values are : ")

for fru in (fruit):

print(fru)


xo = {}

xo[fruit.apple] = 'sweet'

xo[fruit.cherry] = 'sour'


if xo=={fruit.apple : 'sweet',fruit.cherry : 'sour'}:

print ("Enum is hashed")

else: print ("Enum is not hashed")
Output:
All the enum values are : 

fruit.apple

fruit.banana

fruit.cherry

Enum is hashed

>

Python Training Certification

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Accessing Enums

There are 2 ways of accessing enums. One is - accessing by value and another is - accessing by names.

Accessing by value: The value of enum members will be passed in this method.

Accessing by name: The name of the enum member will be passed in this method.

Below is a python code to demonstrate how a user can access enums using python:

import enum

class fruits(enum.Enum):

   apple = 1

   banana = 2

print('enum member accessed by name: ')

print (fruits['apple'])

print('enum member accessed by Value: ')

print (fruits(1))
Output:
enum member accessed by name: 

fruits.apple

enum member accessed by Value: 

fruits.apple

>

  Top 50 frequently asked Python interview Question and answers !

Comparing Enums

The process of comparing the enums is done using the comparison operator in a straightforward manner. There are 2 ways of comparing enums. One is - identity and another is - equality.

Identity: The value of identity is checked using ‘is’ and ‘is not’.

Equality: The comparisons inequality are checked using “==” and “!=” types.

Below is a python code to demonstrate how a user can compare enums using python:

import enum

class fruits(enum.Enum):

   apple = 1

   banana = 2

   cherry = 1

if fruits.apple == fruits.cherry:

   print('There is a match')

if fruits.banana != fruits.cherry:

   print('There is no match')
Output:
There is a match

There is no match

>

Below is a python code to understand both accessing and comparison in python under the same scenario:

import enum

class fruit(enum.Enum):

apple = 1

banana = 2

cherry = 3


print ("The enum member having value 2 is : ",end="")

print (fruit(2))


print ("The enum member having name cherry is : ",end="")

print (fruit['cherry'])

mem = fruit.apple


print ("The value associated with apple is : ",end="")

print (mem.value)


print ("The name associated with apple is : ",end="")

print (mem.name)


if fruit.apple is fruit.banana:

print ("Apple and banana are similar fruits")

else : print ("Apple and banana are different fruits")


if fruit.cherry != fruit.banana:

print ("Cherry and banana are different")

else : print ("cherry and banana are same")
Output:
The enum member having value 2 is : fruit.banana

The enum member having name cherry is : fruit.cherry

The value associated with apple is : 1

The name associated with apple is : apple

Apple and banana are different fruits

Cherry and banana are different

>

Enum Auto values

The enum.auto() method is known to automatically assign an integer value to the values of the enum class simply by using enum.auto() method in python.

Below is the syntax to write auto values in python enum.

enum.auto()

Below is a python code to demonstrate how the user is able to assign the numerical values automatically by using the auto() method in python.

from enum import Enum, auto

class fruit(Enum):

apple = auto()

banana = auto()

cherry = auto()

print(list(fruit))
Output:
[, , ]

>

Subscribe to our youtube channel to get new updates..!

Int Enum

The Enum.intEnum() method allows the user to get the enumeration which is based on an integer value. If we compare it with the basic enum class, it will not succeed using the Enum.IntEnum() method. The syntax for this method is written below:

enum.intEnum()

Below is a python code to demonstrate enumerations using intEnum() method in python.

from enum import IntEnum

class website(IntEnum):

Training = 1

For = 2

Students = 3

print(website.For == 2)
Output:
True

>

Custom Ordering

As we have discussed earlier, python enumerations are actually classes. Hence, the user can add various methods and implement them and customize their behaviors under the enum class.

We can create customized orders with this python method.

Let us see an example below to create a customized order and see what it returns:

from enum import Enum

class Payment(Enum):

    Pending = 1

    Complete = 2

    Refund = 3

    def __str__(self):

        return f'{self.name.lower()}({self.value})'


    def __eq__(self, other):

        if isinstance(other, int):

            return self.value == other


        if isinstance(other, Payment):

            return self is other


        return False

if Payment.Pending == 1:

    print('The status of payment is pending.')
Output:
The status of payment is pending.

>

If you want to Explore more about Python? then read our updated article - Python Tutorial!

Python Training Certification

Weekday / Weekend Batches

Conclusion

In this article, we have discussed in detail the uses of Enum in python. Enum is a python class used to create enumerations, and these are a set of unique and non-variable values denoted using symbols. We have also discussed the whole enum module and its accessing types, comparison types, and examples. We have also covered different methods that come under enumeration, such as enum auto(), enum intEnum(), etc.

Related Articles

1. Python Generators

2. Python Ogre

3. Python IDEs

Find our upcoming Python Training Certification Online Classes

  • Batch starts on 24th Mar 2023, Fast Track batch

  • Batch starts on 28th Mar 2023, Weekday batch

  • Batch starts on 1st Apr 2023, Weekend batch

Global Promotional Image
 

Categories

Request for more information

Gayathri
Gayathri
Research Analyst
As a senior Technical Content Writer for HKR Trainings, Gayathri has a good comprehension of the present technical innovations, which incorporates perspectives like Business Intelligence and Analytics. She conveys advanced technical ideas precisely and vividly, as conceivable to the target group, guaranteeing that the content is available to clients. She writes qualitative content in the field of Data Warehousing & ETL, Big Data Analytics, and ERP Tools. Connect me on LinkedIn.

Python Enum FAQ's

Python enum can be implemented using “enum“ which is actually a module name. Python enum can be created by the user using classes. They have names as well as associated values in python.

Enums in python is used for defining non-variable values such as numbers, strings, etc. They cannot define an indefinite set of states in python, and only set states such as day of the week, etc.

Enums make the python code readable. Enums are int by default, hence the only thing that has to get going is checking again and again regarding the values of int. Hence, a user can have a definite set of enums to make the code flexible as well as readable.

Enums can be used to represent the finite number of data such as days in a month, days of the week, months in a year, etc.

Protected by Astra Security