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?
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"
But you might want to have a look at the code snippet Constants in Python by Alex Martelli.
const keyword as in other languages, however it is possible to create a Property that has a "getter function" to read the data, but no "setter function" to re-write the data. This essentially protects the identifier from being changed.
Here is an alternative implementation using class property:
Note that the code is far from easy for a reader wondering about constants. See explanation below
def constant(f): def fset(self, value): raise TypeError 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 ##TypeError: None
constantthat takes an expression, and uses it to construct a "getter" - a function that solely returns the value of the expression.
constantfunction we just created as a decoration to quickly define read-only properties.
And in some other more old-fashioned way:
(The code is quite tricky, more explanations below)
class _Const(object): @apply def FOO(): def fset(self, value): raise TypeError 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 ##TypeError: None
Note that the @apply decorator seems to be deprecated.
propertyfunction to construct an object that can be "set" or "get".
propertyfunction's first two parameters are named