Constants in Python
Python has no true immutable constants at the language level, but conventions and typing help communicate intent.
Naming convention
Use UPPER_CASE identifiers to indicate constants. Tools and peers recognize this convention.
PI = 3.14159
API_URL = "https://api.example.com"
WELCOME = "Hello"
typing.Final
Annotate names with Final to signal they shouldn’t be reassigned (checked by static type checkers like mypy).
from typing import Final
MAX_RETRIES: Final = 3
TIMEOUT_S: Final[float] = 2.5
Reassignments may be flagged by linters/type checkers.
Immutability of objects
Even if a name is constant, the referenced object may be mutable. Prefer immutable types or protect mutations.
NAMES = ("Ada", "Guido") # tuple (immutable)
CONFIG = {"debug": False} # mutable mapping
# CONFIG["debug"] = True # allowed; consider Mapping or dataclasses.replace
Modules as namespaces
Group related constants in modules to keep code organized.
# constants.py
DEFAULT_ENCODING = "utf-8"
BUFFER_SIZE = 8192
Import explicitly to clarify usage:
from constants import DEFAULT_ENCODING
Enums for constrained values
Use enum.Enum when a name must be one of a small set of values with type safety.
from enum import Enum
class Status(Enum):
PENDING = "pending"
RUNNING = "running"
DONE = "done"
Summary
- Use UPPER_CASE and
typing.Finalto mark constants - Prefer immutable objects or protect mutable ones
- Consider
Enumfor closed sets of allowed values; modules act as namespaces