PYTHON

Define Clear, Named Constants with Python `Enum`

Learn to use Python's `enum` module to create symbolic names (constants) for unique values, improving code readability and preventing hardcoded magic strings or numbers in your applications.

from enum import Enum, auto

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

class UserRole(Enum):
    ADMIN = auto()
    EDITOR = auto()
    VIEWER = auto()

# Accessing enum members
print(f"HTTP Status OK: {HttpStatusCode.OK}")
print(f"OK value: {HttpStatusCode.OK.value}")
print(f"OK name: {HttpStatusCode.OK.name}")

# Comparing enums
response_code = HttpStatusCode.OK
if response_code == HttpStatusCode.OK:
    print("Request was successful.")

# Iterating over enums
print("
All User Roles:")
for role in UserRole:
    print(f"  {role.name}: {role.value}")

# Getting enum member by value (can raise ValueError if not found)
error_404 = HttpStatusCode(404)
print(f"Status for 404: {error_404.name}")

# Using auto() for sequential values
print(f"Admin role value: {UserRole.ADMIN.value}")
print(f"Editor role value: {UserRole.EDITOR.value}")
How it works: The `enum` module allows creation of enumerations, which are sets of symbolic names bound to unique, constant values. This significantly improves code readability and maintainability by replacing 'magic numbers' or strings with meaningful names. `auto()` provides automatic, sequential integer values for enum members, simplifying their definition and ensuring uniqueness without manual assignment.

Need help integrating this into your project?

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

Hire DigitalCodeLabs