Python Enums

Enums in Python define named constants. They provide a way to create a set of named values, enhancing code readability and maintainability compared to using simple integer constants.

Example 1: Simple Enum


from enum import Enum

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

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

Defines a set of named colors (RED, GREEN, BLUE) with associated integer values.

Example 2: Using Enums in a Function


from enum import Enum

class Direction(Enum):
  NORTH = 1
  SOUTH = 2
  EAST = 3
  WEST = 4

def move(direction):
  if isinstance(direction, Direction):
    print(f"Moving {direction.name}ward")
  else:
    print("Invalid direction")

move(Direction.NORTH) # Output: Moving NORTHward
move(1) # Output: Invalid direction
    

Demonstrates how to use an enum for representing directions in a function. It checks for the type of the input to handle invalid input.

Example 3: Enum with Custom Methods


from enum import Enum

class Status(Enum):
  ACTIVE = 1
  INACTIVE = 0

  def is_active(self):
    return self.value == 1

print(Status.ACTIVE.is_active()) # Output: True
print(Status.INACTIVE.is_active()) #Output: False
    

Demonstrates adding methods to an enum to add custom functionality and checking if a status is active.

Example 4: A more robust enum


from enum import Enum, unique

@unique
class AnimalType(Enum):
  DOG = 1
  CAT = 2
  BIRD = 3


print(AnimalType.DOG.value) # Output: 1
    

Use the `@unique` decorator to ensure enum members are unique. This prevents accidental creation of members with the same name.

Important Considerations

  • Readability and Maintainability: Enums provide a clear and concise way to represent named constants, making code easier to read and maintain.
  • Type Safety: Using `isinstance(direction, Direction)` improves type safety, preventing unexpected errors when functions handle enum values.
  • Unique Values: The `@unique` decorator ensures all values are unique; otherwise, Python will raise a ValueError.