Enum in Python

Enum in Python
(Last Updated On: 22/05/2023)

Enum class in Python

# Enum in Python

# import enum
from enum import Enum

class Day(Enum):
	MONDAY = 1
	TUESDAY = 2
	WEDNESDAY = 3
	THURSDAY = 4
	FRIDAY = 5
	SATURDAY = 6
	SUNDAY = 7

# printing enum member as string
print(Day.MONDAY)

# printing name of enum member using "name" keyword
print(Day.MONDAY.name)

# printing value of enum member using "value" keyword
print(Day.MONDAY.value)

# printing the type of enum member using type()
print(type(Day.MONDAY))

# printing enum member as repr
print(repr(Day.MONDAY))

# printing all enum member using "list" keyword
print(list(Day))

Output:

Day.MONDAY
MONDAY
1
<enum 'Day'>
<Day.MONDAY: 1>
[<Day.MONDAY: 1>, <Day.TUESDAY: 2>, <Day.WEDNESDAY: 3>, <Day.THURSDAY: 4>, <Day.FRIDAY: 5>, <Day.SATURDAY: 6>, <Day.SUNDAY: 7>]

Enum in Python Using Accessing Modes

# Enum in Python Using Accessing modes 


from enum import Enum

class Season(Enum):
	SPRING = 1
	SUMMER = 2
	AUTUMN = 3
	WINTER = 4

# Accessing enum member using value
print("The enum member associated with value 2 is : ", Season(2).name)

# Accessing enum member using name
print("The enum member associated with name WINTER is : ", Season['WINTER'].value)

Output:

The enum member associated with value 2 is :  SUMMER
The enum member associated with name WINTER is :  4

Printing enum as an iterable

# Enum in Python  


import enum
# Using enum class create enumerations
class Days(enum.Enum):
   SUNDAY = 1
   MONDAY = 2
   TUESDAY = 3
# printing all enum members using loop
print ("The enum members are : ")
for weekday in (Days):
   print(weekday)

Output:

The enum members are : 
Days.SUNDAY
Days.MONDAY
Days.TUESDAY

Hashing enums

# Enum in Python 


import enum
# Using enum class create enumerations
class Days(enum.Enum):
   Sun = 1
   Mon = 2
# Hashing to create a dictionary
Daytype = {}
Daytype[Days.Sun] = 'Sunday'
Daytype[Days.Mon] = 'Monday'

# Checking if the hashing is successful
print(Daytype =={Days.Sun:'Sunday',Days.Mon:'Monday'})

Output:

True

Comparing the enums

# Enum in Python 


import enum
# Using enum class create enumerations
class Days(enum.Enum):
   Sun = 1
   Mon = 2
   Tue = 1
if Days.Sun == Days.Tue:
   print("sunday is equal to tuesday :",'Match')
if Days.Mon != Days.Tue:
   print("monday is not equal to tuesday:",'No Match')

Output:

sunday is equal to tuesday : Match
monday is not equal to tuesday: No Match

Leave a Reply

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