Declare module-level constants in UPPER_SNAKE_CASE with typing.Final annotations (e.g., MAX_RETRIES: Final[int] = 3) for static type-checker enforcement, or group related constants into an enum.Enum / StrEnum when defining a fixed set of discrete choices—using a frozen @dataclass(frozen=True) when bundling structured configuration groups at runtime.

Basic Example

from dataclasses import dataclass
from enum import StrEnum
from typing import Final

# 1. Recommended (PEP 8 + PEP 591): Module-level UPPER_SNAKE_CASE with typing.Final
MAX_CONNECTIONS: Final[int] = 100
DEFAULT_TIMEOUT: Final[float] = 5.0
API_BASE_URL: Final[str] = "[https://api.example.com/v1](https://api.example.com/v1)"


# 2. Recommended for fixed sets of related choices: StrEnum (Python 3.11+) or Enum
class Environment(StrEnum):
    DEVELOPMENT = "dev"
    STAGING = "staging"
    PRODUCTION = "prod"


# 3. Runtime-immutable structured constant group: Frozen dataclass
@dataclass(frozen=True)
class RetryPolicy:
    max_attempts: int = 3
    backoff_seconds: float = 0.5


RETRY_POLICY: Final[RetryPolicy] = RetryPolicy()

print(MAX_CONNECTIONS)                  # Output: 100
print(Environment.PRODUCTION == "prod") # Output: True

Key Details & Edge Cases

  • Python does not enforce constant immutability at runtime by default:
    • UPPER_SNAKE_CASE is a PEP 8 naming convention, and typing.Final is enforced statically by type checkers (mypy, pyright, IDE linters) rather than the CPython interpreter—meaning MAX_CONNECTIONS = 200 will flag a linter/type error without raising a runtime exception.
  • Avoid mutable objects (list, dict, set) as module-level constants:
    • Even with Final[list[str]], Final only prevents rebinding the variable name (ALLOWED_ROLES = [...]), not mutating its contents (ALLOWED_ROLES.append("guest"))!
    • Always use immutable equivalents for collection constants: tuple (("admin", "editor")) instead of list, frozenset instead of set, and types.MappingProxyType({"a": 1}) when you need a read-only dictionary.
  • StrEnum / IntEnum vs. plain Enum:
    • Standard enum.Enum members do not compare equal to raw strings or integers (Color.RED == "red" evaluates to False), which causes subtle bugs when serializing JSON or comparing API payloads.
    • Inherit from enum.StrEnum (Python 3.11+) or enum.IntEnum when constant members must work seamlessly as str or int values while still supporting Environment("prod") validation and iteration.
  • Class-level constants (ClassVar vs. Final):
    • Inside a class definition, annotate shared constants with ClassVar[Final[int]] = 60 (or Final[int] = 60 on plain classes, which type checkers treat as class-level) so dataclasses and linters do not mistake the constant for an instance field.
  • Centralizing constants (constants.py):
    • Place shared domain constants in a dedicated constants.py module with zero business-logic imports so any module in your project can import them without risking circular ImportError issues.

Comparison of Constant Definition Patterns in Python

Pattern Syntax Enforced by Type Checkers (mypy/pyright)? Enforced at Runtime? Best Used When
UPPER_SNAKE_CASE + Final MAX_RETRIES: Final[int] = 3 Yes (blocks reassignment) No Standalone scalar or immutable tuple/frozenset module constants (PEP 8 default).
enum.StrEnum / IntEnum class Status(StrEnum): OK = "ok" Yes Yes (raises AttributeError on mutation) Fixed domain categories, status codes, or CLI/API string/int choices.
@dataclass(frozen=True) @dataclass(frozen=True) class Config: ... Yes Yes (raises FrozenInstanceError) Grouping related, structured configuration constants into an immutable object.
types.MappingProxyType HEADERS: Final = MappingProxyType({...}) Yes Yes (raises TypeError on item assignment) Read-only lookup tables and constant key-value mappings.
Plain UPPER_SNAKE_CASE PI = 3.14159 No No Quick scripts or minimal codebases without static type checking.