Skip to content
Related Articles

Related Articles

Create Constant Variable in Python using Pconst Library
  • Last Updated : 03 Mar, 2021

Constant variable the name itself says that it is constant. We have to define a constant variable at the time of declaration. After that, we will not able to change the value of a constant variable. In some cases, constant variables are very useful.

Creating constant variables, functions, objects is allowed in languages like c++, Java. But in python creating constant variable, it is not allowed. There is no predefined type for a constant variable in Python. But we can use pconst library for that.

Installation:

pip install pconst

Below are some examples which depict how to use constants in python

Example 1:



You can set constants to const module’s attribute.

Python3




# import module
from pconst import const
  
# declare constants
const.LANGUAGE = "PYTHON"
const.COMPANY_NAME = 'GFG'
  
# display
print(const.LANGUAGE)
print(const.COMPANY_NAME)

Output:

Example 2:

If try to update the constant value, ConstantError will be raised.

Python3




# import module
from pconst import const
  
# declare constants
const.LANGUAGE = "PYTHON"
const.COMPANY_NAME = 'GFG'
  
# update
const.LANGUAGE="C++"

Output:



Example 3:

The del operator is disallowed.

Python3




# import module
from pconst import const
  
# declare constants
const.LANGUAGE = "PYTHON"
const.COMPANY_NAME = 'GFG'
  
# delete
del const.LANGUAGE

Output: 

Example 4: 

You can also set dict and list value to const module, and they will be not editable (if dict or list values contains dict or list, then will be applied recursively.).

Python3




# import module
from pconst import const
  
# define dictionary
const.COMPANY_DATA = {
    'Name': "GFG",
    'Language': ["C", "C++"
                 "Python"]}
  
# display
print('Name:', const.COMPANY_DATA['Name'])
print('Language:', const.COMPANY_DATA['Language'])

Output:

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :