Enum class in Python

1. What is an Enum?

An Enum, or enumeration, is a Python method of declaring a set of related, constant values. This serves to:

  • Increase the readability and self-documentation of the code.
  • Prevent the use of “magic numbers” or hardcoded values.
  • Ensure a set of values remains unchanged and unmovable.

To use an Enum, you need to import it from the enum module.

2. Importing the Enum Class

from enum import Enum

3. Defining an Enum

You define an enumeration by subclassing the Enum class. Members (attributes) are defined as class variables.

Example:

from enum import Enum

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

Output:

This creates an enumeration called Color with three members: RED, GREEN, and BLUE, each assigned a unique value (1, 2, 3).

4. Accessing Enum Members

You can access members of an enum by name or value.

Example:

print(Color.RED)        # Access by name
print(Color(1))         # Access by value
print(Color.RED.name)   # Get the name of the member
print(Color.RED.value)  # Get the value of the member

Output:

Color.RED
Color.RED
RED
1

5. Iterating Over Enum Members

You can iterate over all members of an enumeration using a for loop.

Example:

for color in Color:
    print(color)

Output:

Color.RED
Color.GREEN
Color.BLUE

6. Ensuring Unique Values

By default, enum values must be unique. If you try to define duplicate values, Python raises a ValueError. You can enforce this with the @unique decorator.

Example Without @unique (Error):

from enum import Enum

class Animal(Enum):
    DOG = 1
    CAT = 1  # Duplicate value!

Output:

ValueError: duplicate values are not allowed

Example With @unique:

from enum import Enum, unique

@unique
class Animal(Enum):
    DOG = 1
    CAT = 2

Output:

This will run without errors because all values are unique.

7. Comparison of Enum Members

Enum members are comparable using == and !=.

Example:

print(Color.RED == Color.RED)   # True
print(Color.RED == Color.BLUE)  # False

Output:

True
False

8. Enum Methods

The Enum class provides useful built-in methods to work with its members.

Example:

print(Color.RED.name)   # Get the name of the member
print(Color.RED.value)  # Get the value of the member

# List all enum members and their values:
print(list(Color))  # Returns a list of all members

Output:

RED
1
[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]

9. Auto-Assigning Values

You can use auto() to automatically assign values to enum members, starting from 1 and incrementing automatically.

Example:

from enum import Enum, auto

class State(Enum):
    ON = auto()
    OFF = auto()
    SLEEP = auto()

for state in State:
    print(f"{state.name} = {state.value}")

Output:

ON = 1
OFF = 2
SLEEP = 3

10. Customizing Enums

You can add custom methods or override existing behavior for your enum members.

Example:

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

    def describe(self):
        return f"{self.name} is color number {self.value}"

print(Color.RED.describe())

Output:

RED is color number 1

11. Functional API

You can create an enum dynamically using the functional API instead of the class-based approach.

Example:

from enum import Enum

Status = Enum('Status', 'PENDING IN_PROGRESS COMPLETED')

print(Status.PENDING)
print(Status.PENDING.name)
print(Status.PENDING.value)

Output:

Status.PENDING
PENDING
1

12. Accessing the Member Map

Every enum class has a hidden dictionary-like attribute _member_map_ that stores all members.

Example:

print(Color._member_map_)

Output:

{'RED': <Color.RED: 1>, 'GREEN': <Color.GREEN: 2>, 'BLUE': <Color.BLUE: 3>}

13. Enum Use Cases

Enums are actually useful when you know you have a fixed set of constants, such as:

  1. Representing Human Readable states (e.g., traffic lights, order statuses).
  2. Avoiding “magic numbers” (e.g., numeric codes for HTTP status).
  3. Improve code readability and maintainability.