☼
⌃
☰

Enums in Python

Table of Contents

Enums in Python

Basic Usage

To define an enum, you create a class that inherits from enum.Enum. The members are defined as class attributes.

PYTHON
from enum import Enum

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

Accessing Enum Members

You can access enum members by their names. Each member has name and value properties.

Accessing a Member

PYTHON
current_color = Color.GREEN`

Comparing Members

PYTHON
if current_color is Color.GREEN:
    print("The color is green.") # Output: The color is green.

Accessing name and Value

PYTHON
print(f"Name: {current_color.name}")   # Output: Name: GREEN
print(f"Value: {current_color.value}") # Output: Value: 2

Key Features and Benefits

  • Readability: Using Color.RED is much clearer and less error-prone than using a raw integer like 1.
  • Maintainability: If the underlying value needs to change, you only need to update it in the enum definition.
  • Type Safety: You can use enums in type hints to ensure that functions only accept valid values, preventing bugs.
PYTHON
def set_background(color: Color):
    # function implementation...
    pass

set_background(Color.BLUE) # Valid
# set_background(4) # Invalid, a static type checker would flag this
  • Iteration: You can iterate over the members of an enum.
PYTHON
for color in Color:
    print(color)
# Output:
# Color.RED
# Color.GREEN
# Color.BLUE
  • Automatic Values

The enum module also provides an auto() helper to automatically assign integer values to members, which is useful when the specific value is not important.

PYTHON
from enum import Enum, auto

class State(Enum):
    PENDING = auto()   # Value will be 1
    RUNNING = auto()   # Value will be 2
    COMPLETED = auto() # Value will be 3