Avatar

Blogging tips

Avatar

Python, Django and Flask

Avatar

Latest tech posts

Tuesday, February 25, 2020

Constants in python - The workaround!

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?
Image result for constants



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.py
RATIO_FEET_TO_METERS = 3.281
RATIO_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_KG
from constants import RATIO_FEET_TO_METERS
print(RATIO_LB_TO_KG) # 3.281
print(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_KG
print(RATIO_LB_TO_KG) # 3.281
RATIO_LB_TO_KG = 1
print(RATIO_LB_TO_KG) # 1


No comments:

Post a Comment