Hi,
Is there a way to declare a constant in Python. In java we can create constant in this manner:
public static final String CONST_NAME = "Name";
What is the equivalent of the above java constant declaration in python ?
Cheers,
Hi,
Is there a way to declare a constant in Python. In java we can create constant in this manner:
public static final String CONST_NAME = "Name";
What is the equivalent of the above java constant declaration in python ?
Cheers,
No there is not. You cannot declare a variable or value as constant. 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"
BUt you might want to have a look at the code snippet Constants in Python by Alex Martelli.
In python usually language enforcing something, people use naming conventions e.g __method for private and I have seen people using _method for protected methods i.e. generally not used from outside of class but derived class may override it.
So in same manner you can simple declare the constant as all caps e.g.
MY_CONSTANT = "one"
If you really want that this constant never gets changed, you can hook into attribute access and do tricks, but IMO a simpler approach is to declare a function
def MY_CONSTANT():
return "one"
Only problem is everywhere you will have to do MY_CONSTANT(), but again MY_CONSTANT = "one" is the correct way in python(usually).
The Pythonic way of declaring "constants" is basically a module level variable:
RED = 1
GREEN = 2
BLUE = 3
And then write your classes or functions. Since constants are almost always integers, and they are also immutable in Python, you have a very little chance of altering it.
Unless, of course, if you explicitly set RED = 2.
Here is an alternative implementation using class property
class _Const(object):
@apply
def FOO():
def fset(self, value):
raise SyntaxError
def fget(self):
return 0xBAADFACE
return property(**locals())
CONST = _Const()
print CONST.FOO
##3131964110
CONST.FOO = 0
##Traceback (most recent call last):
## ...
## CONST.FOO = 0
##SyntaxError: None
Or you prefer @decorator style syntax:
def constant(f):
def fset(self, value):
raise SyntaxError
def fget(self):
return f()
return property(fget, fset)
class _Const(object):
@constant
def FOO():
return 0xBAADFACE
@constant
def BAR():
return 0xDEADBEEF
CONST = _Const()
print CONST.FOO
##3131964110
CONST.FOO = 0
##Traceback (most recent call last):
## ...
## CONST.FOO = 0
##SyntaxError: None