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.

Easy Python 3.4+ Aug 9, 2026 OOP & classes 15 views 0 copies

Python code

16 lines
Python 3.4+
from 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

stdout
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

  1. Use `IntEnum` for status codes when you need to compare directly with integers
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.