PYTHON
Defining Fixed Choices with `enum.Enum`
Implement robust, readable, and type-safe choices for states, types, or categories in your Python web applications using the `enum.Enum` module, enhancing data consistency.
from enum import Enum
# Define an Enum for Order Status
class OrderStatus(Enum):
PENDING = 'pending'
PROCESSING = 'processing'
SHIPPED = 'shipped'
DELIVERED = 'delivered'
CANCELLED = 'cancelled'
def __str__(self):
return self.value
# Use the Enum values
current_status = OrderStatus.PROCESSING
print(f"Current order status: {current_status}")
# Comparison
if current_status == OrderStatus.PROCESSING:
print("Order is currently being processed.")
# Iterating through Enum members
print("All possible order statuses:")
for status in OrderStatus:
print(f"- {status.name}: {status.value}")
# Getting an Enum member by its value
status_from_string = OrderStatus('shipped')
print(f"Status from string 'shipped': {status_from_string}")
# Enums are hashable and can be used as dictionary keys
status_descriptions = {
OrderStatus.PENDING: "Awaiting confirmation.",
OrderStatus.DELIVERED: "Successfully delivered to customer."
}
print(f"Delivered status description: {status_descriptions[OrderStatus.DELIVERED]}")
How it works: `enum.Enum` provides a way to define a set of named constant values, which are incredibly useful for representing fixed choices like application states, user roles, or product types in web development. Enums improve code readability, prevent typos, and offer type safety compared to using raw strings or integers, ensuring consistent data handling across your application.