Define an Enum for Status Codes in Python
Create a readable StatusCode enum with HTTP-style status values and iterate over its members using the standard library Enum class.
Python code
16 linesfrom enum import Enum
class StatusCode(Enum):
OK = 200
CREATED = 201
BAD_REQUEST = 400
UNAUTHORIZED = 401
NOT_FOUND = 404
INTERNAL_ERROR = 500
if __name__ == "__main__":
code = StatusCode.NOT_FOUND
print(f"Name: {code.name}")
print(f"Value: {code.value}")
print(f"Is it OK? {code is StatusCode.OK}")
print(f"All codes: {list(StatusCode)}")
Output
Name: NOT_FOUND
Value: 404
Is it OK? False
All codes: [<StatusCode.OK: 200>, <StatusCode.CREATED: 201>, <StatusCode.BAD_REQUEST: 400>, <StatusCode.UNAUTHORIZED: 401>, <StatusCode.NOT_FOUND: 404>, <StatusCode.INTERNAL_ERROR: 500>]
How it works
The Enum class from the standard library gives each member a fixed identity and a .name plus .value attribute. Using is comparisons works reliably because each enum member is a singleton. Iterating with list(StatusCode) returns members in definition order, useful for validation loops. This pattern centralizes status values so you avoid magic numbers scattered across the codebase.
Common mistakes
- Using string comparison like `code == 'NOT_FOUND'` instead of `code is StatusCode.NOT_FOUND`
- Defining enum values as strings when an integer is more natural for HTTP codes
- Forgetting that enum members are singletons, so `==` and `is` both work but `is` is more explicit
Variations
- Use `IntEnum` for status codes when you need to compare directly with integers
- Add custom methods to the enum for grouping, like `def is_error(self)` for codes >= 400
Real-world use cases
- Mapping HTTP response codes to readable labels in an API client or server handler.
- Replacing hardcoded magic numbers in a payment gateway integration with named statuses.
- Validating webhook event types by iterating over all members of a status enum.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.