How do I create a constant in Python?
This question explains the common practices for creating constants in Python, including naming conventions and using modules or classes to prevent unintended changes.
In Python, there’s no built-in keyword like const (like in JavaScript or C++) to define a constant. However, by following a few conventions and best practices, you can still create variables that are treated as constants.
1. Use All Uppercase Naming
The most common way to define a constant is by naming the variable in all uppercase letters:
PI = 3.14159
MAX_USERS = 100
- This signals to other developers that these values shouldn't be changed.
- It’s just a convention though—Python won't stop you from reassigning them.
2. Define Constants in a Separate Module
You can also create a separate Python file, like constants.py, to store all your constants:
# constants.py
API_KEY = "your_api_key"
TIMEOUT = 30
# main.py
from constants import API_KEY
Keeps your code cleaner and easier to maintain.
3. Use typing.Final (Python 3.8+)
If you’re using type hints, Python 3.8 introduced Final from the typing module:
from typing import Final
PI: Final = 3.14159
This tells tools like linters and type checkers that PI shouldn't be reassigned.
Remember:
- Python won’t enforce immutability—it's up to you (and your team) to follow these conventions.
- Using all caps is the widely accepted standard in the Python community.
So, while you can't technically create a constant in Python, you can get pretty close with clear naming and good habits!