PYTHON

Define Symbolic Constants with Python's `enum.Enum`

Use `enum.Enum` in Python to create sets of symbolic, immutable constants, improving code clarity, maintainability, and preventing magic string/number errors in web applications.

from enum import Enum, auto

# Define an Enum for user roles
class UserRole(Enum):
    ADMIN = "admin"
    EDITOR = "editor"
    VIEWER = "viewer"
    GUEST = "guest"

# Define an Enum for HTTP status codes (using auto for simple values)
class HttpStatus(Enum):
    OK = auto()     # 1
    CREATED = auto() # 2
    BAD_REQUEST = auto() # 3
    NOT_FOUND = auto() # 4

# Accessing enum members
print(f"Admin role: {UserRole.ADMIN}")
print(f"Admin role value: {UserRole.ADMIN.value}")
print(f"Admin role name: {UserRole.ADMIN.name}")

# Comparison and usage
current_role = UserRole.EDITOR
if current_role == UserRole.EDITOR:
    print("User has editor privileges.")

# Iterating through enum members
print("All User Roles:")
for role in UserRole:
    print(f"- {role.name}: {role.value}")

# Getting a member by value
role_from_value = UserRole("admin")
print(f"Role from 'admin' value: {role_from_value}")

# Accessing auto-assigned values
print(f"HTTP Status OK value: {HttpStatus.OK.value}")
print(f"HTTP Status NOT_FOUND value: {HttpStatus.NOT_FOUND.value}")

# Enums prevent invalid states
try:
    invalid_role = UserRole("super_admin")
except ValueError as e:
    print(f"Error creating invalid role: {e}")
How it works: The `enum.Enum` module provides a way to create sets of symbolic names (members) bound to unique, constant values. This is incredibly useful in web development for defining fixed choices like user roles, payment statuses, order types, or configuration options, replacing prone-to-error "magic strings" or numbers. Enums improve code readability, make debugging easier, and prevent invalid state assignments. Members can be compared directly, iterated over, and retrieved by their value, offering a robust and self-documenting approach to managing categorical data. The `auto()` function automatically assigns unique integer values.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs