Explore Courses Blog Tutorials Interview Questions
+3 votes
in Python by (210 points)

Is there a way to declare a constant in Python? In Java we can create constant values in this manner:

public static final String CONST_NAME = "Subject";

What is the equivalent of the above Java constant declaration in Python? 

2 Answers

+4 votes
by (10.9k points)
edited by

You can use namedtuple to create constants-

from collections import namedtuple

def make_consts(name, **kwargs):

return namedtuple(name, kwargs.keys())(**kwargs)

 Alternatively , if you are in a class use:

class abc(object):

CONST_NAME = "Subject"

 And, if you are not in a class then just use:


Learn python programming from an industry expert, enroll in our Python programming course

+2 votes
by (108k points)
edited by

No there is not. You cannot able to declare a variable or value as constant in Python. Just don't change it.

If you are inside a class, the equivalent would be:

class Foo(object): CONST_NAME = "Name"

if not, it is just


You can also use namedtuple to create constants:

>>> from collections import namedtuple 

>>> Constants = namedtuple('Constants', ['pi', 'e']) 

>>> constants = Constants(3.14, 2.718) 

>>> constants.pi 3.14 

>>> constants.pi = 3 

Traceback (most recent call last): 

    File "<stdin>", line 1, in <module> 

AttributeError: can't set attribute

You can use the following video tutorials to clear all your doubts:-

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 14, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
asked Jan 18, 2020 in Python by Rajesh Malhotra (19.9k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories