PYTHON

Defining Enumerated Constants with Python's enum.Enum

Organize and manage sets of related, named constants in Python using the `enum.Enum` module for improved code readability and safety.

from enum import Enum

class UserRole(Enum):
    ADMIN = "admin"
    EDITOR = "editor"
    VIEWER = "viewer"
    GUEST = "guest"

class HTTPStatus(Enum):
    OK = 200
    CREATED = 201
    BAD_REQUEST = 400
    UNAUTHORIZED = 401
    NOT_FOUND = 404
    INTERNAL_SERVER_ERROR = 500

# Accessing enum members
print(f"Admin role: {UserRole.ADMIN}")
print(f"Admin role value: {UserRole.ADMIN.value}")
print(f"HTTP Status OK name: {HTTPStatus.OK.name}")
print(f"HTTP Status Not Found value: {HTTPStatus.NOT_FOUND.value}")

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

# Comparing enum members
current_role = UserRole.EDITOR
if current_role == UserRole.ADMIN:
    print("User is an admin.")
elif current_role == UserRole.EDITOR:
    print("User is an editor.")

# Using enum values in logic
status_code = HTTPStatus.OK.value
if status_code == HTTPStatus.OK.value:
    print("Request was successful.")

# Getting enum member by value or name
role_from_value = UserRole("viewer")
print(f"Role from value 'viewer': {role_from_value}")

# role_from_value_error = UserRole("non_existent") # This would raise ValueError
How it works: This snippet introduces `enum.Enum`, a powerful Python module for creating sets of symbolic names (members) bound to unique constant values. `Enums` improve code readability by replacing 'magic strings' or numbers with meaningful names, prevent typos, and provide a clear, type-safe way to define categories or states. Members can be accessed by name or value, and they support iteration and comparison, making them ideal for managing application constants like user roles or HTTP status codes.

Need help integrating this into your project?

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

Hire DigitalCodeLabs