+4 votes
2 views
in Python by (220 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

+5 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:

CONST_NAME=”Subject”

+2 votes
by (90.8k 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

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

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

Related questions

0 votes
1 answer
asked Oct 14, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
0 votes
1 answer
asked Jan 18 in Python by Rajesh Malhotra (14.5k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 10, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...