PYTHON
Define Fixed Choices and States with enum.Enum
Master Python's `enum.Enum` to create clearly defined, constant sets of choices or states, improving data integrity and readability in your web applications.
from enum import Enum
class OrderStatus(Enum):
PENDING = 'pending'
PROCESSING = 'processing'
SHIPPED = 'shipped'
DELIVERED = 'delivered'
CANCELLED = 'cancelled'
class UserRole(Enum):
ADMIN = 'admin'
EDITOR = 'editor'
VIEWER = 'viewer'
# Example usage
current_order_status = OrderStatus.PENDING
print(f"Current status: {current_order_status.value}") # Access the string value
# Comparison
if current_order_status == OrderStatus.PENDING:
print("Order is awaiting processing.")
# Iterating through enum members
print("All order statuses:")
for status in OrderStatus:
print(f"- {status.name}: {status.value}")
# Getting enum member from value (e.g., from database or API)
status_from_db = 'shipped'
try:
retrieved_status = OrderStatus(status_from_db)
print(f"Retrieved status from DB: {retrieved_status}")
except ValueError:
print(f"Invalid status value: {status_from_db}")
# Using in a function signature
def update_order(order_id: int, new_status: OrderStatus):
print(f"Updating order {order_id} to status: {new_status.value}")
# Logic to update database...
update_order(101, OrderStatus.PROCESSING)
# update_order(102, 'invalid_status') # This would raise a TypeError with static type checking
How it works: The `enum.Enum` module provides a way to create enumerations, which are sets of symbolic names (members) bound to unique, constant values. This is crucial in web development for defining fixed choices, such as order statuses, user roles, or product categories. Enums improve code readability by replacing "magic strings" or numbers with meaningful names, prevent typos, and enable easy validation of input values. They ensure consistency across your application and can be particularly useful when interacting with databases or external APIs that use predefined status codes.