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.
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.
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.
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.
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.