Python Guide Sidebar

Python – Enums

Introduction to Enums in Python

Firstly, Enums (short for Enumerations) in Python provide a way to define a set of named constant values that remain unchanged throughout a program. Furthermore, they make code more readable, maintainable, and less error-prone. In addition, they eliminate the need for magic numbers or hardcoded values.

Python introduced the enum module in Python 3.4, allowing developers to create and use enumerations efficiently.

Why Use Enums?

Enums are useful in various scenarios:

  • Code Readability: Named constants improve clarity.
  • Error Prevention: Prevents accidental modification of values.
  • Grouping Constants: Organizes related values together.
  • Type Safety: Restricts a variable to predefined values.

Properties of Enums in Python

Enums in Python have unique characteristics that make them useful in various applications:

  1. Uniqueness – Each enum member has a distinct value and name.
  2. Immutable – Enum values cannot be changed after assignment.
  3. Type-Safety – Prevents invalid values from being used.
  4. Ordered – Enum members retain their defined order.
  5. Supports Iteration – Enums can be looped over easily.
  6. Comparison Support – Enums support identity (is) and equality (==) comparisons.
  7. Namespace Containment – Enum members are grouped within a class.

Advantages of Using Enums

  • Improves Readability – Named constants are easier to understand than magic numbers.
  • Enhances Maintainability – Reduces the chances of using incorrect or inconsistent values.
  • Prevents Accidental Modification – Once defined, enum members cannot be altered.
  • Better Debugging – Using meaningful names simplifies troubleshooting.
  • Supports Iteration and Membership Checks – Makes it easy to loop through members or check if a value is valid.

Disadvantages of Using Enums

  • Slightly More Overhead – Enums add a small performance cost compared to plain constants.
  • Learning Curve – Beginners might find Enums complex initially.
  • Limited Modification – Once defined, members cannot be changed dynamically.
  • Can Be Overkill – For simple constants, Enums might be unnecessary.
Creating an Enum in Python

To define an enumeration, we use the Enum class from the enum module.

Example 1: Basic Enum
from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

print(Color.RED)        
print(Color.RED.value)  
print(Color.GREEN.name) 
Explanation:
  1. Firstly, the Color class inherits from Enum, making it an enumeration.
  2. Moreover, each member of Color is assigned a unique value.
  3. Additionally,.value retrieves the associated value, while .name gets the member’s name.
Accessing Enum Members

We can access enum members using their name or value.

print(Color(1))        
print(Color['GREEN'])  
Iterating Over Enum Members
for color in Color:
    print(color)
Comparing Enums

Enums support identity and equality comparisons:

print(Color.RED == Color.RED)  
print(Color.RED is Color.GREEN)
Advanced Enum Features
1. Assigning Custom Values
from enum import Enum

class StatusCode(Enum):
    SUCCESS = "200 OK"
    NOT_FOUND = "404 Not Found"
    INTERNAL_ERROR = "500 Internal Server Error"

    def get_code(self):
        return int(self.value.split()[0])

    def get_description(self):
        return ' '.join(self.value.split()[1:])

# Example usage:
print(StatusCode.SUCCESS.get_code())
print(StatusCode.SUCCESS.get_description())
2. Auto Assigning Values

Using auto() to automatically assign values:

from enum import Enum, auto

class Rank(Enum):
    FIRST = auto()
    SECOND = auto()
    THIRD = auto()

    def get_marks(self):
        """Returns the marks associated with the rank."""
        marks = {
            Rank.FIRST: 100,
            Rank.SECOND: 80,
            Rank.THIRD: 60,
        }
        return marks[self]

    def __str__(self):
        return f"{self.name.title()} (Position {self.value}, Marks: {self.get_marks()})"

# Example usage:
if __name__ == "__main__":
    for rank in Rank:
        print(rank)
3. Extending Enums
from enum import Enum

class ExtendedColor(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
    YELLOW = 4
Enum Use Cases

Enums are widely used in game development, API responses, error handling, and configuration settings. For example:

Example: Using Enums for HTTP Status Codes
class HTTPStatus(Enum):
    OK = 200
    BAD_REQUEST = 400
    NOT_FOUND = 404

print(HTTPStatus.NOT_FOUND)

Example: Using Enums for Days of the Week

class Day(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3

Summary

  • Enums improve code readability, maintainability, and safety.
  • Furthermore, they restrict variables to predefined values, ensuring better control over data.
  • Additionally, using Enum, auto(), and name/value properties provides flexibility in implementation.

Additional Topics:


Interview Questions:

1. What are Enums in Python, and why are they useful?(Google)
Answer:
Enums (Enumerations) in Python are a way to define a set of named constant values. As a result, they help improve code readability, maintainability, and prevent accidental modifications of values. Moreover, Enums restrict a variable to specific predefined values, which makes the code less error-prone.


2. How does Python ensure that Enum members are unique, and what happens if duplicate values are assigned?(Amazon)
Answer:
By default, Python Enums prevent duplicate values. When two members share the same value, Python automatically treats the second member as an alias of the first.

Example:

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 1  # Duplicate value

print(Color.RED is Color.BLUE)

#However, we can enforce strict uniqueness by using the @unique decorator from enum:

from enum import Enum, unique

@unique
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 1  

3. How can you use auto() in Enums, and what are its benefits?(Microsoft)

Answer:
The auto() function in the enum module automatically assigns values to enum members, eliminating the need for manual numbering. It is useful when values don’t matter but uniqueness does.

Benefits of auto():

  • Avoids manual numbering mistakes
  • Ensures uniqueness automatically
  • Reduces redundancy in defining values

Quizz time with Python Enums