Create a constant in Python

0 votes

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 = "Name";

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

Aug 24, 2018 in Python by bug_seeker
• 15,510 points
28,930 views

1 answer to this question.

0 votes

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

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

class Foo(object): CONST_NAME = "Name"

if not, it is just

CONST_NAME = "Name"

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

Hope this helps!!

If you need to learn more about Python, It's recommended to join Python Training today.

Thanks!

answered Aug 24, 2018 by Priyaj
• 58,020 points

Related Questions In Python

0 votes
1 answer

How do I create a constant in Python?

Hello @kartik, No there is not. You cannot ...READ MORE

answered Nov 19, 2020 in Python by Niroj
• 82,840 points
1,458 views
+2 votes
2 answers

How can I create a new file in Python?

You can try the below code which ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,440 points
1,339 views
0 votes
1 answer

Create and open a file in Python

file = open('text.txt', 'w+) READ MORE

answered May 24, 2018 in Python by Nietzsche's daemon
• 4,260 points
897 views
0 votes
1 answer

Create a nested directory in Python

Try os.path.exists, and consider os.makedirs for the ...READ MORE

answered Oct 16, 2018 in Python by SDeb
• 13,300 points
1,628 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,466 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
4,127 views
+1 vote
1 answer

How to create plots using python matplotlib in IPython notebook?

I think you should try: I used %matplotlib inline in ...READ MORE

answered Aug 8, 2018 in Python by Priyaj
• 58,020 points
1,619 views
0 votes
1 answer

Best way to create a simple python web service

web.py is probably the simplest web framework ...READ MORE

answered Jul 20, 2018 in Python by Priyaj
• 58,020 points
921 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP