Enum

The enum module (introduced in Python 3.4) allows you to define a set of symbolic names (constants) bound to unique values. It is helpful for creating readable and maintainable code.

What is an Enum?

  • An Enum is a class where each member represents a constant value.
  • Useful for defining categories or states in a program.

How to Define an Enum

Use the Enum class to define enums.

Example:

Python
Copy
from enum import Enum

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

print(Color.RED)       # Output: Color.RED
print(Color.RED.name)  # Output: RED
print(Color.RED.value) # Output: 1

Iterate Over Enum

You can loop through all members of an Enum.

Example:

Python
Copy
for color in Color:
    print(color.name, color.value)
# Output:
# RED 1
# GREEN 2
# BLUE 3

Access Enum Members

Access members using their names or values.

Example:

Python
Copy
print(Color['RED'])  # Output: Color.RED
print(Color(2))      # Output: Color.GREEN

Auto Value Enums

Use auto() to assign values automatically.

Example:

Python
Copy
from enum import Enum, auto

class Status(Enum):
    PENDING = auto()
    APPROVED = auto()
    REJECTED = auto()

print(Status.PENDING.value)  # Output: 1