Coming from a Java background, I am used to using the final keyword to ensure a variable cannot be reassigned. How do I achieve this same behavior in Python to define global constants like an API_URL or a DATABASE_PORT? Is there a built-in keyword for this in the latest Python 3 versions, or is it strictly a naming convention that developers must follow to prevent accidental data modification?
3 answers
In Python, there is no strict "constant" keyword that prevents reassignment at runtime. Instead, Python relies on the PEP 8 naming convention: you should name your variable in all capital letters with underscores, like MAX_CONNECTIONS = 100. This signals to other developers that the value should not be changed. For better enforcement during development, you can use the Final type hint from the typing module, such as TOTAL: Final = 50. While this doesn't stop the code from running if the value changes, static type checkers like Mypy will flag it as an error, providing a much cleaner development workflow.
Are you looking for a way to enforce these constants at the class level, or are you just trying to keep your global configuration file organized for a large-scale application?
The standard is simply using UPPER_CASE names. Python is built on a philosophy of "we are all consenting adults," meaning we trust developers to respect the naming convention.
Michelle is right. Python prioritizes flexibility. If you really need to lock a value down, you'd have to use a custom @property decorator without a setter in a class, but that’s usually overkill for simple constants.
Mark, if it's for a large-scale application, I’d suggest putting all constants into a separate config.py file. Then, you can import them across the whole project. This keeps the logic and the data separate. Even though Python won't physically block a change to config.API_KEY, having a dedicated file makes it much less likely that a teammate will accidentally overwrite it in the middle of a functional loop.