You can wrap a constant in a numpy array, flag it write only, and always call it by index zero.
import numpy as np
# declare a constant
CONSTANT = 'hello'
# put constant in numpy and make read only
CONSTANT = np.array([CONSTANT])
CONSTANT.flags.writeable = False
# alternatively: CONSTANT.setflags(write=0)
# call our constant using 0 index
print 'CONSTANT %s' % CONSTANT[0]
# attempt to modify our constant with try/except
new_value = 'goodbye'
try:
CONSTANT[0] = new_value
except:
print "cannot change CONSTANT to '%s' it's value '%s' is immutable" % (
new_value, CONSTANT[0])
# attempt to modify our constant producing ValueError
CONSTANT[0] = new_value
>>>
CONSTANT hello
cannot change CONSTANT to 'goodbye' it's value 'hello' is immutable
Traceback (most recent call last):
File "shuffle_test.py", line 15, in <module>
CONSTANT[0] = new_value
ValueError: assignment destination is read-only
of course this only protects the contents of the numpy, not the variable "CONSTANT" itself; you can still do:
CONSTANT = 'foo'
and CONSTANT
would change, however that would quickly throw an TypeError the first time CONSTANT[0]
is later called in the script.
although... I suppose if you at some point changed it to
CONSTANT = [1,2,3]
now you wouldn't get the TypeError anymore. hmmmm....
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.setflags.html