PYTHON
Defining Clear Application States with Python enum.Enum
Use Python's enum.Enum to create symbolic, immutable constants for application states, user roles, or data types, enhancing code readability, maintainability, and preventing magic string errors.
from enum import Enum, auto
# Define user roles in a web application
class UserRole(Enum):
ADMIN = auto() # Automatically assigns a unique value
EDITOR = auto()
VIEWER = auto()
GUEST = auto()
# You can also assign explicit values
# ADMIN = 100
# EDITOR = 50
# VIEWER = 10
# GUEST = 1
# Define order statuses
class OrderStatus(Enum):
PENDING = "pending"
PROCESSING = "processing"
SHIPPED = "shipped"
DELIVERED = "delivered"
CANCELLED = "cancelled"
# Example usage
current_user_role = UserRole.ADMIN
order_status = OrderStatus.PROCESSING
print(f"Current user role: {current_user_role.name} (Value: {current_user_role.value})")
print(f"Order status: {order_status.name} (Value: {order_status.value})")
# Comparisons
if current_user_role == UserRole.ADMIN:
print("User has administrative privileges.")
if order_status.value == "processing": # Can compare with value
print("Order is currently being processed.")
# Iterating through enum members
print("
All User Roles:")
for role in UserRole:
print(f"- {role.name}")
# Using enums in functions
def grant_access(role: UserRole):
if role in (UserRole.ADMIN, UserRole.EDITOR):
print(f"Access granted for {role.name}.")
else:
print(f"Access denied for {role.name}.")
grant_access(UserRole.ADMIN)
grant_access(UserRole.GUEST)
# Avoiding magic strings/numbers
# Instead of: if status_string == "shipped":
if order_status == OrderStatus.SHIPPED:
print("Order has been shipped.")
How it works: The enum.Enum module provides a way to define sets of symbolic names (members) bound to unique, constant values. This is incredibly useful in web development for representing fixed sets of choices like user roles, order statuses, payment methods, or configuration settings. Enums improve code readability by replacing "magic strings" or numbers with meaningful names, prevent typos from causing hard-to-debug errors, and enable better type checking, leading to more robust and maintainable applications.