Alright, let's talk about constants.
What are Constants?
A constant is just like a variable, but once you give it a value, youβre not supposed to change it.
Does Python Even Have Constants?
No. Not really. Other languages let you declare a variable that can't be changed. Python doesn't. Any "constant" you create can be reassigned later. It's a dynamic language, which is the root cause.
So what do we do? We use a convention. It's a universal "please don't change this" sign for other developers (and your future self).
The Convention
It's simple: if a variable's value should not change, write its name in all uppercase letters, using underscores to separate words.
Examples:
MAX_CONNECTIONS = 100
API_KEY = "a1b2c3d4-e5f6-7890-ghij-klmnopqrstuv"
DEFAULT_TIMEOUT = 30
This is the standard, as laid out in PEP 8 (Python's style guide). When a programmer sees a variable named API_KEY
, they know it's not meant to be altered anywhere in the code.
Why Bother?
If the language doesn't enforce it, what's the point?
- Readability: Constant immediately tells anyone reading the code that this value is fixed and important. It makes the code's intent clearer.
- Maintainability: If you need to change a value that's used in 20 different places (like a timeout setting), you only have to change it in one spot: where the constant is defined. This is better than hunting for a "magic number" like
30
scattered throughout your script. - Safety: It prevents you or someone else from accidentally overwriting a critical value, because the all-caps naming serves as a strong warning.
Where Do You Define Them?
Usually, at the module level. That means at the top of your .py
file, right after the imports.
# my_script.py
import os
# --- Constants ---
MAX_RETRIES = 3
API_ENDPOINT = "https://api.example.com/v1/"
# --- Functions ---
def fetch_data():
# function code uses API_ENDPOINT
pass
# --- Main execution ---
if __name__ == "__main__":
# script logic uses MAX_RETRIES
pass
For larger projects, some people put all their constants in a dedicated constants.py
or config.py
file and import them where needed. This keeps things organized.