Python has not defined a constant variable data type, however, we can use other way to implement it. In this tutorial, we will discuss how to create a constant variable in python.
What is constant variable
If a variable is constant, which means the value of this variable can not be changed or edited.
How to create a constant variable in python?
We provides two methods to create python constant variable.
Method 1: Create a python class to make the property cannot be edited.
Here is an example.
class Constant(object): def __init__(self, val): super(Constant, self).__setattr__("value", val) def __setattr__(self, name, val): raise ValueError("Trying to change a constant value", self)
Then you can use this Constant class to create a python constant variable.
PI = Constant(3.14) print(PI.value) PI.value = 3.1415926 print(PI.value)
Run this code, you will find PI = 3.14. However, if you assign a new value to PI, it will report error.
Method 2: Use python pconst library
Python pconst library can allow us to create a python constant variable.
To use it, you should install this library first.
pip install pconst
How to create a python constant variable using pconst?
Here is an example:
from pconst import const const.PI = 3.14 print(const.PI) const.PI = 3.1415926 print(const.PI)
We have created a python constant variable const.PI, we can not change its value.
Run this code, you will find this result.