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.
Sorry Dear! First method is not perfect!
PI = Constant(3.14)
PI.__dict__[‘value’] = 3.1415926
print(PI.value)
3.1415926
MY METHOD:
from types import MappingProxyType
from functools import wraps
import sys
class Const(object):
class Temp:
__attributes = MappingProxyType({})
@staticmethod
def __exception_handler__(func):
@wraps(func)
def handler(*args, **kwargs):
try:
func(*args, **kwargs)
except AssertionError as error:
errors = {
‘constant’ : ‘Constant variable cannot be assigned a value’,
‘magicMethod’ : ‘Magic method cannot be assign a method’
}
print(‘Error: %s’ % errors[str(error)])
return handler
def __init__(self, **kwargs):
self.temp_ = Const.Temp()
for var, value in kwargs.items():
super(Const, self).__setattr__(var, value)
def __concat__(self, **kwargs):
return MappingProxyType(kwargs)
@property
def __dict__(self):
return self.temp_._Temp__attributes
@__exception_handler__
def __setattr__(self, var, value):
try:
assert not(var.endswith(‘__’) and var.startswith(‘__’)), ValueError(‘magicMethod’)
assert not self.__getattribute__(var), ValueError(‘constant’)
except AttributeError:
super(Const, self).__setattr__(var, value)
self.temp_._Temp__attributes = self.__concat__(**dict(self.temp_._Temp__attributes), **{var : value})
def __repr__(self, *args):
return self.__getattribute__(args[0]) if args else super(Const, self).__repr__()
”’
#Example
const_var = Const(t1=’Test String 1′, t2 = 1)
const_var.t3 = [1,2,3,4]
print(const_var.t1)
# Output: Test String 1
const_var.t1 = ‘Test String 2′
# Output: Error: Constant variable cannot be assigned a value
print(const_var.t1)
# Output: Test String 1
const_var.t2 += 1
# Output: Error: Constant variable cannot be assigned a value
print(const_var.t2)
# Output: 1
print(const_var.t3)
# Output: [1,2,3,4]
const_var.t3.append(5)
# Output: [1,2,3,4,5]
# But Immutable objects cannot be changed!
const_var.t3 = [1,2,3,4]
# Output: Error:Constant variable cannot be assigned a value
print(const_var.t3)
# Output: [1,2,3,4,5]
”’