You've successfully subscribed to Better Data Science
Great! Next, complete checkout for full access to Better Data Science
Welcome back! You've successfully signed in
Success! Your account is fully activated, you now have access to all content.

Python Constants - Everything You Need to Know

Python Constants - Everything You Need to Know

Does Python have constants? Read to find out.

Python Constants contribute to the dynamic and updatable characteristic of the design architecture, which is essential for any coding architecture. Providing a construction with these features is related to the fact that the code blocks can be understood and developed by someone else.

To meet those versatile conditions, the expressions in code should be clear, unambiguous, and uncomplicated. Programming languages have many useful expressions to provide these kinds of flexibilities. In this article - Constants - one of them, is analyzed in detail and supported by coding implementations in Python.


What are Constants in Python?

Constants are one of the building blocks of programming languages and one of the facilities that provide the necessary flexibility for users. As the name implies, constants are units that allow users to assign values that cannot be edited after they are defined.

The tricky point here is that although a constant cannot be edited, it can be updated. On the other hand, there are cases where constants are mutable and these are discussed in detail with examples in the next section. A Python example of a case where constants are immutable is as follows:

VALUE = "Python"
VALUE[0] = 'X'
Image 1 - Unsupported item assignment error (image by author)
Image 1 - Unsupported item assignment error (image by author)

It is intended to change the first letter of the word "Python" assigned to the VALUE  "Xython", but it is impossible to change it. VALUE is defined as a constant and cannot be edited. When the code block above runs, the error, "TypeError: 'str' object does not support item assignment.", occurs. If we want to get the word "Xython", we need to assign it to a new value just like VALUE which we defined the word "Python". It is also possible to update the constant "Python" to "Xython" by assigning it to VALUE.

The facilitating effect of constants on the models developed is also undeniable. A certain number, text, list, or tuple can be used in more than one place in the program.

For example, let's imagine that we will import more than one dataset from different links locally or over the Internet. In this case, in each operation, this link must be introduced separately to the command to be re-imported. However, if this link is assigned to a certain constant, and this expression is written where the link is needed in the run, it will be sufficient to change only this assigned link instead of changing the data in the entire code block one by one. It will also make the code system more understandable and easier to manage.

Constants are usually assigned to expressions consisting of capital letters, of course, they are not mandatory, but they are like a kind of culture developed by developers over time.

Similarly, values such as "int" or "float", like "str" values, can be assigned to certain constants, making the construction of the coding model more efficient. For example, parameters such as image width and image height used in image processing appear in more than one place in the work. When these expressions are assigned to IMAGE_WIDTH and IMAGE_HEIGHT as constants at the beginning of the run, changing only the values at the beginning of the code block will save changing the entire structure and would provide convenience.

In C programming language, when assigning data, it is defined by adding expressions such as "int", that is, integer, which determines the data type. Python, on the other hand, provides convenience in this case and assigns the data type itself. For example:

X = 22
print(type(X))

Y = 22.22
print(type(Y))

VALUE = "Python"
print(type(VALUE))

When the type of constants is examined by running the above code block, the output is:

Image 2 - Code block output (image by author)
Image 2 - Code block output (image by author)

Although not specified by the user, it assigned the number 22 as an integer, 22.22 as float, and the word "Python" as a string. Of course, these types can also be assigned by the user as follows:

X = float(22)
print(type(X))

Y = str(22.22)
print(type(Y))

print("Length of Y:", len(Y))

When the float value 22.22 is defined as a string, each object is defined as an element. Since there are 4 "2" values and 1 “.”, the length value is 5:

Image 3 - Code block output (2) (image by author)
Image 3 - Code block output (2) (image by author)

Constants in Python for Data Types

There are 2 types of objects: mutable - objects that can be modified (edited) after they are created, and immutable - objects that cannot be modified (edited) after they are created.

Python data types where constants are mutable:

  • Dict
  • List
  • Set

A simple list object type is constructed and observed to be modified as follows:

CONTINENTS = ["Asia", "Europe", "Africa"]
print(CONTINENTS)

CONTINENTS[1] = "Antartica"
print(CONTINENTS)

print(type(CONTINENTS))

The output of the above code block is:

Image 4 - Code block output (3) (image by author)
Image 4 - Code block output (3) (image by author)

Changing Europe to Antarctica in the CONTINENTS list was a success. Since the Python list object is mutable, Python performed the operation without any error.

Python data types where constants are immutable:

  • int
  • tuple
  • unicode
  • float
  • string
  • bool

The above error message occurred when int, float, and string types are changed. The same is done below for the tuple type:

X = (1,2,3)
print(type(X))
X[1] = 25

The value "2", the second element of the tuple type constant defined as X, wanted to be replaced with "25". Outputs are as follows:

Image 5 - Code block output (4) (image by author)
Image 5 - Code block output (4) (image by author)

What needs to be done here is to redefine X = (1, 25, 3) to avoid this sort of error.


Named Constants in Python

A named tuple structure is a class type that maps the given values under the collections module. The constants assigned with this mapping process can be easily passed through the prepared operations.

With a more concrete example: Let's assume that the weight of the quiz in a class is 30% and the final exam is 70% and calculate the average of the students using namedtuple:

from collections import namedtuple

Grade = namedtuple('Grade', 'quiz final_exam')

student_1 = Grade(60.0, 75.0)
student_2 = Grade(60.0, 90.0)


def average_grade(student_ID):
    student_ID_average = (student_ID.quiz) * 0.3 + (student_ID.final_exam) * 0.7
    return student_ID_average


student_1_average = average_grade(student_1)
student_2_average = average_grade(student_2)

Grade is assigned quiz and final_exam results through mapping with namedtuple. After these results are retrieved by the user in student_1, student_2 format, the average_grade function is created as above. As a result, the average grade was calculated with the quiz exam weighted 30% and the final exam weighted 70%.


Constants in Python Classes

There are 2 types of constants in the coding structure: local constants and global constants. If constants are defined outside the class and def block, they are called global constants, if they are defined inside, they are called local constants. To call a constant in a class in another class:

class Value:
    constant_f = 30.05
    constant_s = "Hello World"

class FinalValue(Value):
    def const(self):
        print("float constant is:", self.constant_f, "\n","string constant is:", self.constant_s)

value_in_class = FinalValue()
value_in_class.const()

constant_f is assigned a float value of 30.05 and constant_s is assigned a string value of "Hello World". The above code block is used to call this in the FinalValue class. The output is:

Image 6 - Code block output (5) (image by author)
Image 6 - Code block output (5) (image by author)

Conclusion

The constant structure has a very important place not only in Python but in all programming languages. It makes the constructed system more understandable and makes the work easier.

Since Python is a user-friendly programming language in terms of syntax, it provides a very favorable environment for the use of constants. Operations that can be done with longer code blocks can be done with less workload with the understanding of constants.

What's your take on constants in Python? Let me know in the comment section below.

Stay connected