Python Useful Modules — enum

Tony
5 min readNov 26, 2023

What is enum Module

Enums, short for “enumerations,” are a programming construct that allows you to define a set of named values, creating a more expressive and maintainable codebase. The enum module in Python provides a dedicated and elegant way to work with enumerations, making your code clearer, more self-documenting, and less prone to errors.

Here’s a simple example of how to use the Python enum module:

import enum

# Define an enumeration class named 'Color'
class Color(enum.Enum):
RED = 1
GREEN = 2
BLUE = 3

# Accessing enum members
print(Color.RED) # Color.RED
print(Color.GREEN) # Color.GREEN
print(Color.BLUE) # Color.BLUE

# Iterating through enum members
for color in Color:
print(color)

# Comparing enum members
selected_color = Color.GREEN
if selected_color == Color.GREEN:
print("Selected color is GREEN")

During the parsing of the class, the Enum’s members are transformed into instances. Each instance possesses a ‘name’ attribute, which corresponds to the member’s name, and a ‘value’ attribute, which corresponds to the value assigned to that name in the class definition.

import enum

# Define an enumeration class named 'Color'
class Color(enum.Enum):
RED = 1
GREEN = 2
BLUE = 3

# Accessing enum members
red_color = Color.RED
green_color…

--

--