In Python, you can implement enums with associated data using several approaches. Here are the most common and effective methods:
Using Enum with Custom Methods
python
from enum import Enum
class Status(Enum):
PENDING = ("pending", "Task is waiting to be processed")
RUNNING = ("running", "Task is currently being executed")
COMPLETED = ("completed", "Task has finished successfully")
FAILED = ("failed", "Task encountered an error")
def __init__(self, code, description):
self.code = code
self.description = description
# Usage
status = Status.PENDING
print(status.code) # "pending"
print(status.description) # "Task is waiting to be processed"
Using Enum with Properties
python
from enum import Enum
class HttpStatus(Enum):
OK = (200, "Success")
NOT_FOUND = (404, "Resource not found")
SERVER_ERROR = (500, "Internal server error")
def __init__(self, code, message):
self.code = code
self.message = message
@property
def is_error(self):
return self.code >= 400
# Usage
status = HttpStatus.NOT_FOUND
print(status.code) # 404
print(status.message) # "Resource not found"
print(status.is_error) # True
from enum import Enum
from dataclasses import dataclass
@dataclass(frozen=True)
class PlanetData:
mass: float # in 10^24 kg
radius: float # in km
class Planet(Enum):
MERCURY = PlanetData(0.330, 2439.7)
VENUS = PlanetData(4.87, 6051.8)
EARTH = PlanetData(5.97, 6371.0)
MARS = PlanetData(0.642, 3389.5)
@property
def surface_gravity(self):
# Simplified calculation
G = 6.67300E-11
return G * self.value.mass * 1E24 / (self.value.radius * 1000) ** 2
# Usage
earth = Planet.EARTH
print(earth.value.mass) # 5.97
print(earth.surface_gravity) # ~9.8
Functional API Approach
python
from enum import Enum
# For simpler cases, you can use the functional API
Color = Enum('Color', [
('RED', ('#FF0000', 'A bright red color')),
('GREEN', ('#00FF00', 'A bright green color')),
('BLUE', ('#0000FF', 'A bright blue color'))
])
# Access the data
print(Color.RED.value[0]) # "#FF0000"
print(Color.RED.value[1]) # "A bright red color"
The first approach with custom __init__ methods is usually the most readable and flexible for most use cases. Choose the method that best fits your data complexity and usage patterns.