Python - use enums to group related constants


Python clean code tip:

Use enums to group related constants.

Why?

  1. Autocomplete
  2. Static type checking

Example:

from dataclasses import dataclass
from enum import Enum

# bad
ORDER_PLACED = "PLACED"
ORDER_CANCELED = "CANCELED"
ORDER_FULFILLED = "FULFILLED"


@dataclass
class Order:
    status: str


order = Order(ORDER_PLACED)
print(order)


# better
class OrderStatus(str, Enum):
    PLACED = "PLACED"
    CANCELED = "CANCELED"
    FULFILLED = "FULFILLED"


@dataclass
class Order:
    status: OrderStatus


order = Order(OrderStatus.PLACED)
print(order)