In languages like Java, we use public static final to declare constants.
But since Python doesn’t have built-in constant declarations, what’s the recommended or conventional approach to working with Python constants so that values remain unchanged throughout the program?
Yeah, Python doesn’t have real constants like Java’s public static final, but we follow naming conventions.
The typical approach is to define constants using all-uppercase variable names at the top of a file or in a separate module:
python
Copy
Edit
PI = 3.14159
MAX_USERS = 100
This doesn’t enforce immutability, but by convention, other developers will treat those as constants and not reassign them.
In our codebase, we create a separate constants.py file where we store all our constants.
That way they’re centrally managed and easily imported like:
python
Copy
Edit
from constants import API_KEY, TIMEOUT
Again, nothing stops someone from changing them, but it’s all about discipline and readability.
If you need stricter enforcement, you might explore making constants with custom classes, but that’s usually overkill.
@MattD_Burch I actually ran into this when I first switched from Java!
If you’re really determined to protect constants, Python doesn’t stop you directly, but you can use namedtuples, Enums, or even custom classes with read-only properties.
For example:
python
Copy
Edit
class _Constants:
@property
def PI(self):
return 3.14
CONSTS = _Constants()
print(CONSTS.PI) # works
CONSTS.PI = 22 # raises an AttributeError
Still, 99% of the time, just naming variables in ALL_CAPS is enough in Python projects.