Python Enums: Defining and Using Enumerations with the Enum Class

Discover how to use the Enum class in Python to create enumerations, assigning fixed constant values to a set of identifiers. Learn how to define enumerations, access their members, and use attributes like name and value to manage and utilize enumeration values effectively in your Python programs.



Python - Enums

In Python, enumeration assigns fixed constant values to a set of strings. The Enum class from the enum module is used to define an enumeration of identifiers, conventionally written in uppercase.

Example

Below, "subjects" is the enumeration with different enumeration members. Each member is an object of the enumeration class subjects, with name and value attributes.


# importing enum 
from enum import Enum

class subjects(Enum):
   ENGLISH = 1
   MATHS = 2
   SCIENCE = 3
   SANSKRIT = 4

obj = subjects.MATHS
print (type(obj))
        
Output


        

An enum class cannot have the same member appearing twice, but multiple members can have the same value. To ensure unique values, use the @unique decorator.

Example with @unique

Using the @unique decorator to restrict duplicate values:


from enum import Enum, unique

@unique
class subjects(Enum):
   ENGLISH = 1
   MATHS = 2
   GEOGRAPHY = 3
   SANSKRIT = 2
        
Output

   @unique
    ^^^^^^
   raise ValueError('duplicate values found in %r: %s' %
ValueError: duplicate values found in : SANSKRIT -> MATHS
        

The Enum class is callable, allowing enumeration creation via its constructor:

Alternative Method

Another way to define an enumeration:


from enum import Enum
subjects = Enum("subjects", "ENGLISH MATHS SCIENCE SANSKRIT")
print(subjects.ENGLISH)
print(subjects.MATHS)
print(subjects.SCIENCE)
print(subjects.SANSKRIT)
        
Output

subjects.ENGLISH
subjects.MATHS
subjects.SCIENCE
subjects.SANSKRIT
        

Accessing Enums

Enum members can be accessed by their value or name:


from enum import Enum

class subjects(Enum):
   ENGLISH = "E"
   MATHS = "M"
   GEOGRAPHY = "G"
   SANSKRIT = "S"
   
obj = subjects.SANSKRIT
print(type(obj))
print(obj.name)
print(obj.value)
        
Output


SANSKRIT
S
        

Iterating through Enums

Enumerations can be iterated through using a for loop:


from enum import Enum

class subjects(Enum):
   ENGLISH = "E"
   MATHS = "M"
   GEOGRAPHY = "G"
   SANSKRIT = "S"

for sub in subjects:
   print(sub.name, sub.value)
        
Output

ENGLISH E
MATHS M
GEOGRAPHY G
SANSKRIT S
        

Enum members can be accessed by their unique value or name attribute:


print(subjects("E"))
print(subjects["ENGLISH"])