Does Python Have Constants?

Does Python Have Constants?

Can you define non-changing values?

Image for postPhoto by Gabriel Crismariu on Unsplash

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 or NUM.
  • 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.pyRATIO_FEET_TO_METERS = 3.281RATIO_LB_TO_KG = 2.205

Next, main.py:

Notice how the constant values are more apparent in the code as well as being outside the file itself. Both of these qualities help communicate the distinction between constant and variable.

If you do not want to continually type constant. you can import values individually:

from constants import RATIO_LB_TO_KGfrom constants import RATIO_FEET_TO_METERSprint(RATIO_LB_TO_KG) # 3.281print(RATIO_FEET_TO_METERS) # 2.205

Unfortunately, after taking all these steps it?s still possible to overwrite the values:

from constants import RATIO_LB_TO_KGprint(RATIO_LB_TO_KG) # 3.281RATIO_LB_TO_KG = 1print(RATIO_LB_TO_KG) # 1

Do you miss using true constants in Python? Do you agree with Python?s decision to exclude them? Leave your thoughts and experiences below!

26