Whether you want to prevent accidental modification, provide type safety in large projects, or improve readability and maintainability, you need constants in your program.
Python does not have any keyword like “const” like a JavaScript to declare a constant. However, we can suggest to other programmers that a variable is a constant by using an all-uppercase variable name with underscores.
Here are different ways to create a constant:
Method 1: Uppercase naming convention
The most standard way to create a constant is to define a variable in all uppercase with sometimes underscores. This tells other developers not to change its value. It is universally understood and based on the PEP 8 official recommendation.
PI = 3.141592653589793
MAX_CONNECTIONS = 100
API_BASE_URL = "https://api.appdividend.com/v1"
SUPPORTED_LANGUAGES = ("en", "es", "fr", "de")
STATUS_ACTIVE = "ACTIVE"
print(PI)
# Output: 3.141592653589793
print(MAX_CONNECTIONS)
# Output: 100
print(API_BASE_URL)
# Output: https://api.appdividend.com/v1
print(SUPPORTED_LANGUAGES)
# Output: ('en', 'es', 'fr', 'de')
print(STATUS_ACTIVE)
# Output: ACTIVE
There is one disadvantage to this approach: it does not enforce immutability.
Developers should understand that they don’t change it. By mistake, if they change it, unexpected results can happen in the future, or errors can occur.
SETTINGS = {"theme": "dark"}
print(SETTINGS)
# Output: {'theme': 'dark'}
SETTINGS["theme"] = "light"
print(SETTINGS)
# Output: {'theme': 'light'}
See, the variable’s value has been changed even though we marked it as a constant.
Method 2: Using typing.Final (Static Type Enforcement)
The typing.Final is a static way of checking if its value is modified and not a runtime mechanism. It prevents reassignment at the type-checking level.
It is best for large codebases that use mypy or PyCharm inspections.
from typing import Final
API_KEY: Final = "SECRET219"
print(f"The API key is: {API_KEY}")
# Output: The API key is: SECRET219
In this code, we imported the built-in typing module and used its Final classifier.
So, we defined a constant API_KEY as Final with the value “SECRET219”.
If you try to modify its value, Static analyzers like mypy or PyCharm will throw an error at compile time.
Runtime still allows modification, but tooling prevents mistakes.
from typing import Final
API_KEY: Final = "SECRET219"
print(f"The API key is: {API_KEY}")
# Output: The API key is: SECRET219
# Attempting to reassign API_KEY
API_KEY = "NEWKEY192"
print(f"The new API key is: {API_KEY}")
# Output: The new API key is: NEWKEY192
Method 3: Immutable constants (namedtuple)
If you want to create a constant whose value is immutable after its creation, you can use the namedtuple from the collections module.
A namedtuple creates a lightweight, immutable object that lets you access its fields like attributes.
from collections import namedtuple
Constants = namedtuple('Constants', ['PI', 'MAX_CONNECTIONS', 'API_BASE_URL'])
constants = Constants(PI=3.14159,
MAX_CONNECTIONS=100,
API_BASE_URL='https://api.appdividend.com/v1')
print(constants.PI)
# Output: 3.14159
print(constants.MAX_CONNECTIONS)
# Output: 100
print(constants.API_BASE_URL)
# Output: https://api.appdividend.com/v1
# Trying to modify a constant will raise an AttributeError
constants.PI = 3.14
print(constants.PI)
# Output: AttributeError: can't set attribute
In this code, we defined three constants using namedtuple and tried to modify the value of PI.
Since namedtuple can’t be modified, it raises an AttributeError: can’t set attribute error, which is a perfect example of immutability.
That’s all!
