/  Technology   /  Python | Enum

Python | Enum

Enumerations are executed by using the module named “enum“in Python.By using classes enumerations are created . Enums have names and values related with them.

 

Features of enum:

 

  1. Enums are shown as string or repr.
  2. Enums use type()to check their types.
  3. Enums uses “name” keyword display the name of the enum member.

 

Example:

 

import enum
# creating enumerations using class
class Animal(enum.Enum):
  ant = 1
  bee = 2
  cat = 3

# printing enum member as string
print ("The string representation is : ",end="")
print (Animal.ant)

# printing enum member as repr
print ("The repr representation is : ",end="")
print (repr(Animal.bee))

# printing the type of enum member
print ("The member type is : ",end ="")
print (type(Animal.cat))

# printing name of enum member
print ("The member name is : ",end ="")
print (Animal.ant.name)

 

Output:

 

Python | Enum

 

  1. Enumerations are iterable. They can be iterated using loops
  2. Enumerations support hashing. Enums can be used in dictionaries or sets.

 

Example:

 

import enum

# creating enumerations using class
class Animal(enum.Enum):
  cat = 1
  bee = 2
  lion = 3

# printing all enum members using loop
print ("All the enum values are : ")
for Anim in (Animal):
print(Anim)

# Hashing enum member as dictionary
di = {}
di[Animal.cat] = 'meows'
di[Animal.lion] = 'roar'

# checking if enum values are hashed successfully
if di=={Animal.cat : 'meows',Animal.lion : 'roar'}:
    print ("Enum is hashed")
else: print ("Enum is not hashed")

 

Output:

 

Python | Enum

 

 

Leave a comment