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 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_CASEis a PEP 8 naming convention, andtyping.Finalis enforced statically by type checkers (mypy,pyright, IDE linters) rather than the CPython interpreter—meaningMAX_CONNECTIONS = 200will 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]],Finalonly 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 oflist,frozensetinstead ofset, andtypes.MappingProxyType({"a": 1})when you need a read-only dictionary.
- Even with
StrEnum/IntEnumvs. plainEnum:- Standard
enum.Enummembers do not compare equal to raw strings or integers (Color.RED == "red"evaluates toFalse), which causes subtle bugs when serializing JSON or comparing API payloads. - Inherit from
enum.StrEnum(Python 3.11+) orenum.IntEnumwhen constant members must work seamlessly asstrorintvalues while still supportingEnvironment("prod")validation and iteration.
- Standard
- Class-level constants (
ClassVarvs.Final):- Inside a class definition, annotate shared constants with
ClassVar[Final[int]] = 60(orFinal[int] = 60on plain classes, which type checkers treat as class-level) so dataclasses and linters do not mistake the constant for an instance field.
- Inside a class definition, annotate shared constants with
- Centralizing constants (
constants.py):- Place shared domain constants in a dedicated
constants.pymodule with zero business-logic imports so any module in your project can import them without risking circularImportErrorissues.
- Place shared domain constants in a dedicated
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. |
|
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. |
You must log in or register to comment.
