Member-only story
Does Python Have Constants?
Can you define non-changing values?

Having transitioned from other languages, including PHP and JavaScript, constants are engrained in my practice.
When I adopted Python, I quickly found myself asking the question, does Python have constants?
The answer is kind of, but not really. Let’s dig deeper!
What is a Constant?
Before we move on, let’s define what a constant is, in case you’re unfamiliar.
A constant value is similar to a variable, with the exception that it cannot be changed once it is set. Constants have a variety of uses, from setting static values to writing more semantic code.
How to Implement Constants in Python
I said earlier that Python “kind of, but not really” has constants. What does that mean? It means that you can follow some standard conventions to emulate the semantic feel of constants, but Python itself does not support non-changing value assignments, in the way other languages that implement constants do.
If you’re like me and mostly use constants as a way of writing clearer code, then follow these guidelines to quasi-implement constants in your Python code:
- Use all capital letters in the name: First and foremost, you want your constants to stand out from your variables. This is even more critical in Python as you can technically overwrite values that you set with the intention of being constant.
- Do not overly abbreviate names: The purpose of a constant — really any variable — is to be referenced later. That demands clarity. Avoid using single letter or generic names such as
N
orNUM
. - Create a separate constants.py file: To add an element of intentional organization in structure and naming, it’s common practice to create a separate file for constants which is then imported.
What does this all look like in practice?
We’ll create two files, constants.py
and app.py
to demonstrate.
First, constants.py
:
# constants.py
RATIO_FEET_TO_METERS = 3.281
RATIO_LB_TO_KG = 2.205