Skip to main content

Python Enum Foundation, Basic and Naming

Β· 5 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

🐍 Python Enum: Foundation, Naming, and Primitive Conversion​

This article focuses on the necessity of the enum.Enum class, proper definition, standard naming conventions, and the fundamental process of converting Enum members to and from primitive types like integers and strings.

When to Use Enums (The "Why")​

You should use the enum.Enum class whenever you have a fixed, finite set of choices or constants in your code.

Primitive AlternativeWhy Enum is BetterExample
Raw Strings ("admin", "guest")Type Safety: The type checker (MyPy) enforces that only valid members (Role.ADMIN) are passed, not typos ("admn").Prevents runtime errors caused by mistyped constant strings.
Magic Numbers (1, 2, 3)Readability: Provides self-documenting names instead of obscure numerical codes.OrderStatus.PROCESSING is clearer than status == 2.
Global ConstantsNamespace Isolation: Keeps constants contained within a single class, avoiding pollution of the global namespace.Prevents name collisions across different parts of a large application.

Python Enum Class Definition and Naming Conventions​

The simplest way to define an enum is by subclassing enum.Enum and assigning values to members.

AspectBest PracticeCode Example
Class NameUse PascalCase and singular nouns (e.g., Color, Status).class UserRole(Enum):
Member NamesUse ALL_CAPS (standard for constants).ADMIN = 'administrator'
ValuesUse meaningful strings or integers.ADMIN = 'administrator'
from enum import Enum, IntEnum

# Foundation Example: String Enum
class UserRole(Enum):
"""Defines user roles using descriptive strings."""
ADMIN = 'administrator'
EDITOR = 'content_editor'
VIEWER = 'read_only'

# Foundation Example: Integer Enum (Using IntEnum for arithmetic)
class HttpCategory(IntEnum):
"""Defines HTTP status categories using numerical ranges."""
INFORMATIONAL = 1
SUCCESS = 2
REDIRECTION = 3
CLIENT_ERROR = 4
SERVER_ERROR = 5

Conversion to Primitive Types (to String, to Int)​

The most common requirement is converting the Enum member object back into its raw value (str or int) for serialization, logging, or database storage.

Conversion TargetAttribute to UseOutput Type
Raw Value.valueThe type assigned when defined (str or int).
Member Name.nameString representing the member name (ADMIN).
# Setup
current_role = UserRole.ADMIN
status_category = HttpCategory.SUCCESS

# Example 1: Enum Member to Raw String Value
role_value_str = current_role.value
print(f"Role Value (str): {role_value_str}")
# Output: administrator

# Example 2: Enum Member to Name String
role_name_str = current_role.name
print(f"Role Name (str): {role_name_str}")
# Output: ADMIN

# Example 3: Enum Member to Raw Integer Value
status_value_int = status_category.value
print(f"Status Value (int): {status_value_int}")
# Output: 2

# Example 4: Integer Enum to Integer Comparison (IntEnum only)
# This works because IntEnum is a subclass of int
if status_category == 2:
print("IntEnum can be directly compared to its value.")

Conversion from Primitive Types (from String, from Int)​

To use an Enum for type safety, you need a reliable way to convert external data (like an integer from a configuration file or a string from an API payload) back into a safe Enum member.

Conversion MethodExampleUsage
Direct CallUserRole('administrator')Uses the Enum class constructor, mapping the primitive value to the member.
Access by NameUserRole['ADMIN']Accesses the member using its name string (must be ALL_CAPS).
# Example 5: From Raw String Value to Enum Member (Direct Call)
input_str = "read_only"
member_from_str = UserRole(input_str)
print(f"Member from string: {member_from_str}")
# Output: UserRole.VIEWER

# Example 6: From Raw Integer Value to Enum Member (Direct Call)
input_int = 5
member_from_int = HttpCategory(input_int)
print(f"Member from integer: {member_from_int}")
# Output: HttpCategory.SERVER_ERROR

# Example 7: From Name String to Enum Member (Dictionary Style)
input_name = "VIEWER"
member_from_name = UserRole[input_name]
print(f"Member from name: {member_from_name}")
# Output: UserRole.VIEWER

# Example 8: Handling Invalid Conversion (Crucial)
try:
UserRole('invalid_string')
except ValueError as e:
print(f"Error on invalid input: {e}")
# Output: Error on invalid input: 'invalid_string' is not a valid UserRole