Constant in Python

  1. Python Constant by Defining a Class
  2. Python Constant Using a Function
  3. Python Constant Using namedtuple() Function

This tutorial will introduce multiple methods to create a constant or achieve constant-like properties in Python. We can not declare a constant in Python, as there is no keyword as const. But we can create our own constant in the following ways.

Python Constant by Defining a Class

One way is to create a class and declare its attribute as read-only to be used as a constant. The below example code demonstrates how to declare the class attribute as read-only in Python.

class constant(object):
    __slots__ = ()
    val = 457

a = constant()

print(a.val)  
a.val = 23

Output:

457
AttributeError: 'constant' object attribute 'val' is read-only

Another way to create a constant in Python is to create a class and override the __setattr__(self, *_) to return the exception whenever someone tries to assign a new value to the class attribute.

We can use a class attribute as a constant in Python in the following way.

class Constant(object):
    CONST = "abcd"

def __setattr__(self, *_):
    raise Exception("Tried to change the value of a constant")

a = Constant()
print(a.CONST)
a.CONST_NAME = "a"

Output:

abcd
Exception: Tried to change the value of a constant

Python Constant Using a Function

We can also create a function that always returns the same value we want to assign to the constant. The below example code demonstrates how to use the function to get the constant value in Python.

def constant():
  return "xyz"

constant()

Output:

xyz

Python Constant Using namedtuple() Function

We can also use the namedtuple(typename, field_names) function of the collections module to create a constant in Python. The namedtuple() function returns a new tuple subclass of name typename, and the field_names are list of string identifiers. As in Python, a tuple is immutable, the value of a new tuple subclass can not be changed so that it can be used as a constant.

The example below demonstrates how to use the namedtuple() function to create a constant in Python.

from collections import namedtuple

my_consts = namedtuple('Constants', ['const1', 'const2'])
consts = my_consts(54, "abc")
print(consts.const1)
print(consts.const2)

Output:

54
abc

Now let’s try to change the value of the tuple.

from collections import namedtuple

my_consts = namedtuple('Constants', ['const1', 'const2'])
consts = my_consts(54, "abc")
consts.const1 = 0

Output:

AttributeError: can't set attribute
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.