Enum in Python

In Python, known for its simplicity and readability, provides a valuable feature called Enum (short for Enumeration) that enhances code clarity and organization. In this blog, we will understand the concept of Enums in Python, from their basic usage to advanced features and real-world applications.

What is Enum in Python?

In Python, an Enum, short for Enumeration, is a distinct data type used to represent a set of named constants, also referred to as enumeration members or enumerators. Enums provide a way to associate meaningful names with a fixed set of values, making the code more readable and self-explanatory.

Example of Enum

# Enum in Python

# import enum
from enum import Enum

class Day(Enum):

# printing enum member as string

# printing name of enum member using "name" keyword

# printing value of enum member using "value" keyword

# printing the type of enum member using type()

# printing enum member as repr

# printing all enum member using "list" keyword


<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>]

Accessing Modes for Enums in Python

The below code display how to create an Enum class representing seasons and how to access Enum members using their values and names:

# Enum in Python Using Accessing modes 

from enum import Enum

class Season(Enum):

# 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)

Explanation of the code:

1. We begin by importing the `Enum` class from the `enum` module in Python.

2. We define an Enum class named `Season`, which represents the four seasons: SPRING, SUMMER, AUTUMN, and WINTER. Each season is associated with a unique integer value.

3. To access Enum members, we have two methods demonstrated in the code:

  • Accessing enum member using value: Here, we use the `Season(2)` syntax, which retrieves the Enum member associated with the value `2`. In this case, it corresponds to `Season.SUMMER`. We then print the name of the Enum member using `.name`.

Accessing enum member using name: In this part of the code, we access the Enum member associated with the name ‘WINTER’ using `Season[‘WINTER’]`. This retrieves the Enum member, and we print its associated value using `.value`.


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

Printing enum as an iterable

Python code below demonstrates the usage of Enums using the `enum` module.

# 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):

Explanation of the code:

1. Import the `enum` module: The code begins by importing the `enum` module, which provides functionality for creating and working with Enumerations.

2. Define an Enum class: The `Days` Enum class is defined with three Enum members, `SUNDAY`, `MONDAY`, and `TUESDAY`, each associated with an integer value (1, 2, and 3, respectively).

3. Iterate through Enum members: A `for` loop is used to iterate through all the members of the `Days` Enum. The loop variable `weekday` takes on the values of each Enum member in turn.

4. Print Enum members: Inside the loop, the code prints each `weekday`, which corresponds to 

an Enum member. The `print(weekday)` statement displays the name of each Enum member.


The enum members are : 

In summary, this code showcases the creation of an Enum class named `Days` with three Enum members. It then uses a loop to iterate through and print the names of all the Enum members. Enums are a useful way to represent a fixed set of named constants in Python.

Hashing enums

Below Python code demonstrates the use of Enums and hashing to create a dictionary for days of the week.

# 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'})

Explanation of the code:

1. `import enum`: The code starts by importing the `enum` module, which is necessary to define Enums in Python.

2. Enum Definition: An Enum class named `Days` is defined using the `enum.Enum` class. It defines two Enum members, `Sun` and `Mon`, associated with integer values 1 and 2, respectively. This Enum represents days of the week.

3. Dictionary Creation: A dictionary named `Daytype` is created to map Enum members to their corresponding day names. In this case, `Days.Sun` is mapped to ‘Sunday,’ and `Days.Mon` is mapped to ‘Monday.’

4. Hashing for Dictionary: The code checks if the hashing to create the dictionary was successful by comparing `Daytype` with a dictionary literal `{Days.Sun: ‘Sunday’, Days.Mon: ‘Monday’}`. The `enum` module automatically ensures that Enum members are hashable, making them suitable as keys in dictionaries.

5. Printing the Result: The code prints the result of the comparison, which will be `True` if the hashing and dictionary creation were successful.



In summary, this code showcases how to define an Enum for days of the week and use hashing to create a dictionary mapping Enum members to their corresponding day names. It demonstrates the convenience of using Enums in Python for such scenarios.

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')

Explanation of the code:

1. An Enum class named `Days` is defined with three Enum members: `Sun`, `Mon`, and `Tue`. Each member is associated with an integer value.

2. The code includes two comparison statements:

  • The first comparison checks if `Days.Sun` is equal to `Days.Tue`. It uses the equality operator (`==`) to compare the two Enum members by their values. Since both `Sun` and `Tue` are associated with the value `1`, the condition evaluates to `True`, and it prints “sunday is equal to tuesday : Match.”
  • The second comparison checks if `Days.Mon` is not equal to `Days.Tue`. It uses the inequality operator (`!=`) to compare `Mon` and `Tue`. Since `Mon` is associated with the value `2`, which is not equal to the value `1` associated with `Tue`, the condition evaluates to `True`, and it prints “monday is not equal to tuesday: No Match.”


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

In summary, this code demonstrates how to define an Enum class and perform equality and inequality comparisons between Enum members based on their associated values.

Real-world Use Cases

Here are some real-world use cases where Enums can greatly improve your Python code.

1. Representing Days of the Week

from enum import Enum, auto

class DaysOfWeek(Enum):
    MONDAY = auto()
    TUESDAY = auto()
    WEDNESDAY = auto()
    THURSDAY = auto()
    FRIDAY = auto()
    SATURDAY = auto()
    SUNDAY = auto()

def get_weekday_message(day):
    if day == DaysOfWeek.SATURDAY or day == DaysOfWeek.SUNDAY:
        return "It's the weekend!"
        return "It's a weekday."

today = DaysOfWeek.FRIDAY

In this example, the `DaysOfWeek` Enum makes it clear and maintainable to represent the days of the week. It helps prevent invalid values and ensures that only valid days are used, improving the robustness of your code.

2. Handling HTTP Status Codes

from enum import Enum

class HttpStatus(Enum):
    OK = 200
    NOT_FOUND = 404
    FORBIDDEN = 403

def handle_response(status_code):
    if status_code == HttpStatus.OK:
        return "Request succeeded."
    elif status_code == HttpStatus.NOT_FOUND:
        return "Resource not found."
    elif status_code == HttpStatus.FORBIDDEN:
        return "Access forbidden."
    elif status_code == HttpStatus.INTERNAL_SERVER_ERROR:
        return "Internal server error."
        return "Unknown status code."

response_status = 404

By using an Enum like `HttpStatus`, you can make your code more expressive and self-documenting when dealing with HTTP status codes. It ensures that you only handle recognized status codes, improving code clarity and reducing the risk of errors.

3. Menu Options in a Command-Line Interface

from enum import Enum

class MenuOptions(Enum):
    NEW_GAME = 1
    LOAD_GAME = 2
    SETTINGS = 3
    QUIT = 4

def show_menu():
    print("Main Menu:")
    for option in MenuOptions:
        print(f"{option.value}. {option.name.replace('_', ' ')}")

user_choice = MenuOptions.LOAD_GAME
if user_choice == MenuOptions.NEW_GAME:
    print("Starting a new game...")
elif user_choice == MenuOptions.LOAD_GAME:
    print("Loading a saved game...")
elif user_choice == MenuOptions.SETTINGS:
    print("Opening settings...")
elif user_choice == MenuOptions.QUIT:
    print("Quitting the game...")

Enums are useful for creating clear and structured menus in command-line interfaces. In this example, `MenuOptions` simplifies menu handling, making it easier to understand and maintain the code.

4. States in a Finite State Machine

from enum import Enum

class TrafficLightState(Enum):
    RED = 1
    YELLOW = 2
    GREEN = 3

class TrafficLight:
    def __init__(self):
        self.state = TrafficLightState.RED

    def change_state(self):
        if self.state == TrafficLightState.RED:
            self.state = TrafficLightState.GREEN
        elif self.state == TrafficLightState.GREEN:
            self.state = TrafficLightState.YELLOW
        elif self.state == TrafficLightState.YELLOW:
            self.state = TrafficLightState.RED

    def get_current_state(self):
        return self.state

traffic_light = TrafficLight()
print("Initial state:", traffic_light.get_current_state())
print("After one change:", traffic_light.get_current_state())

In this case, Enums help represent the states of a traffic light in a Finite State Machine. The code becomes more readable, and it’s easy to see the possible states and transitions, which enhances maintainability.

By incorporating Enums into your Python code, you can improve code clarity and maintainability by providing meaningful names to constants and ensuring that only valid values are used in various contexts. This reduces the likelihood of bugs and makes your code more self-explanatory, saving time and effort in the long run.

In Python, Enums are a powerful tool for enhancing code readability and maintainability. They provide a structured way to define constants, making your code more self-documenting. Whether you’re representing days of the week, HTTP status codes, or menu options, Enums simplify your code and reduce the risk of errors. Start using Enums in your Python projects today to write cleaner and more robust code.

Our blog post on “Enums in Python” is here to assist you with all your Python-related questions. For further enriching your coding skills, explore Newtum’s website, where you can discover our online coding courses in Java, C++, PHP, and other programming languages. Elevate your Python expertise and delve into new programming concepts with dedication and hands-on practice.

About The Author

Leave a Reply