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?
I write a util lib for python const: kkconst - pypi support str, int, float, datetime
the const field instance will keep its base type behavior.
For example:
more details usage you can read the pypi url: pypi or github
We can create a descriptor object:
You can wrap a constant in a numpy array, flag it write only, and always call it by index zero.
of course this only protects the contents of the numpy, not the variable "CONSTANT" itself; you can still do:
and
CONSTANT
would change, however that would quickly throw an TypeError the first timeCONSTANT[0]
is later called in the script.although... I suppose if you at some point changed it to
now you wouldn't get the TypeError anymore. hmmmm....
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.setflags.html
In my case, I needed immutable bytearrays for an implementation of a crypto library containing many literal numbers I wanted to ensure were constant.
This answer works but attempted reassignment of bytearray elements does not raise an error.
Constants are immutable, but constant bytearray assignment fails silently:
A more powerful, simple, and perhaps even more 'pythonic' approach involves the use of memoryview objects (buffer objects in <= python-2.6).
ConstArray item assignment is a
TypeError
:There is a cleaner way to do this with namedtuple:
Usage Example
With this exactly approach you can namespace your constants.
I'm probably missing a trick here, but this seems to work for me:
Creating the instance allows the magic
__setattr__
method to kick in and intercept attempts to set theFOO
variable. You could throw an exception here if you wanted to. Instantiating the instance over the class name prevents access directly via the class.It's a total pain for one value, but you could attach lots to your
CONST
object. Having an upper class, class name also seems a bit grotty, but I think it's quite succinct overall.