Python Constants
In this page:
Conceptual Constants
Python has no dedicated const keyword — by convention, developers name a variable in ALL_CAPS (like MAX_RETRIES) to signal to other readers "this value is not meant to change," even though the interpreter itself won't stop you from reassigning it.
Example: Conceptual Constants
MAX_RETRIES = 5
print(MAX_RETRIES)
MAX_RETRIES = 10 # interpreter allows this even though the name signals "don't change me"
print(MAX_RETRIES)
Constant Modules
Grouping related constants into their own module, such as config.py, and importing them where needed keeps settings centralized in one place, so changing a value like an API URL means editing one line instead of hunting through the whole codebase.
Example: Constant Modules
# config.py would hold:
# API_URL = "https://api.example.com"
# Importing it elsewhere: from config import API_URL
API_URL = "https://api.example.com"
print(API_URL)
Numeric Constants
Naming a repeated numeric literal — like MAX_USERS = 100 instead of scattering the bare number 100 throughout your code — turns an unexplained "magic number" into a self-documenting name and makes future changes a one-line edit.
Example: Numeric Constants
MAX_USERS = 100
print(f"Server allows up to {MAX_USERS} users")
String Constants
Fixed text values like error messages, status labels, or a welcome banner are good candidates for named string constants, since hardcoding the same string in multiple places risks the copies drifting out of sync if one gets edited and the others don't.
Example: String Constants
ERROR_NOT_FOUND = "Resource not found"
print(ERROR_NOT_FOUND)
Best Practices for Constants
Placing all constant definitions near the top of a file, before the rest of the logic, makes them easy to find and adjust without having to scroll through unrelated code — a small convention that pays off the moment someone else has to maintain the file.
Example: Best Practices for Constants
MAX_RETRIES = 3
TIMEOUT_SECONDS = 30
def connect():
print("Connecting with timeout", TIMEOUT_SECONDS)
connect()
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: