/  Technology   /  How can I represent an ‘Enum’ in Python?
How can I represent an 'Enum' in Python

How can I represent an ‘Enum’ in Python?

 

Enumerations in python are implemented using the enum module. Enum is a class that creates enumerations, a collection of symbols(members) that tend to have unique and constant values. These members of an enumeration can be accessed and compared. Enumerations are iterable and can be iterated using loops.

 

In the code below, we have imported the enum module and created a class Week and passed enum as its parameter and finally assigned values 1,2 and 3 for the members, Sun, Mon and Tue.

Example:

import enum

class Week(enum.Enum) :
    Sun = 1
    Mon = 2
    Tue = 3

 

 

enums can be displayed using string str and repr representation. To learn more about str and repr representations, refer to the article.

Example:

import enum

class Week(enum.Enum) :
    Sun = 1
    Mon = 2
    Tue = 3
print (The string representation of enum member Sun is : ",end="")
print (Week.Sun)
print (The repr representation of enum member Sun is : ",end="")
print (Week.Sun)

output:

 

We can know the type of enums using the type() function.

type(class_name.member)

Example:

import enum

class Week(enum.Enum) :
    Sun = 1
    Mon = 2
    Tue = 3
print (The type of enum member Sun is : ",end="")
print (type(Week.Sun))

output:

 

Using the name keyword, we can know the name of the respective enum.

Example:

import enum

class Week(enum.Enum) :
    Sun = 1
    Mon = 2
    Tue = 3
print (The name of enum member Sun is : ",end="")
print (Week.Sun.name)

output:

 

We are printing enum members of class Week as an iterable in the code below using a for loop.

Example:

import enum

class Week(enum.Enum) :
    Sun = 1
    Mon = 2
    Tue = 3
for day in (Week):
    print (day)

output:

Leave a comment