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?
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?
Extending Raufio's answer, add a repr to return the value.
then the object behaves a little more like you might expect, you can access it directly rather then '.value'
In addition to the two top answers (just use variables with UPPERCASE names, or use properties to make the values read-only), I want to mention that it's possible to use metaclasses in order to implement named constants. I provide a very simple solution using metaclasses at GitHub which may be helpful if you want the values to be more informative about their type/name:
This is slightly more advanced Python, but still very easy to use and handy. (The module has some more features, including constants being read-only, see its README.)
There are similar solutions floating around in various repositories, but to the best of my knowledge they either lack one of the fundamental features that I would expect from constants (like being constant, or being of arbitrary type), or they have esoteric features added that make them less generally applicable. But YMMV, I would be grateful for feedback. :-)
well.. even though this is outdated, let me add my 2 cents here :-)
Instead of ValueError to break, you can prevent any update happening there. One advantage of this is that you can add constants dynamically in the program but you cannot change once a constant is set. Also you can add any rule or whatsoever before setting a constant(something like key must be a string or a lower case string or upper case string and so on before setting the key)
However, I do not see any importance of setting constants in Python. No optimizations can happen like in C and hence it is something that is not required, I guess.
Here is an implementation of a "Constants" class, which creates instances with read-only (constant) attributes. E.g. can use
Nums.PI
to get a value that has been initialized as3.14159
, andNums.PI = 22
raises an exception.Thanks to @MikeGraham 's FrozenDict, which I used as a starting point. Changed, so instead of
Nums['ONE']
the usage syntax isNums.ONE
.And thanks to @Raufio's answer, for idea to override __ setattr __.
Or for an implementation with more functionality, see @Hans_meine 's named_constants at GitHub
Properties are one way to create constants. You can do it by declaring a getter property, but ignoring the setter. For example:
You can have a look at an article I've written to find more ways to use Python properties.