Activestate has a recipe titled Constants in Python by Martelli for creating a const
module with attributes which cannot be rebound after creation. That sounds like what you're looking for except for the upcasing -- but I suspect that could be added by making it check to see whether the attribute name was all uppercase or not.
Of course, this can be circumvented by the determined, but that's the way Python is -- and it's considered to be a "good-thing" by most of us. To make it harder though, I suggest you do not add the so-called obvious __delattr__
method because people could then just delete names and then add them back rebound to different values.
So here's what I'm taking about:
# from http://code.activestate.com/recipes/65207-constants-in-python
class _const:
class ConstError(TypeError): pass
class ConstCaseError(ConstError): pass
def __setattr__(self, name, value):
if self.__dict__.has_key(name):
raise self.ConstError, "Can't change const.%s" % name
if not name.isupper():
raise self.ConstCaseError, 'const name "%s" is not all uppercase' % name
self.__dict__[name] = value
import sys
sys.modules[__name__] = _const()
if __name__ == '__main__':
import const
try:
const.Answer = 42
except const.ConstCaseError, exc:
print exc
else:
raise Exception, "Non-uppercase only const name shouldn't be allowed!"
const.ANSWER = 42 # OK, all uppercase
try:
const.ANSWER = 17
except const.ConstError, exc:
print exc
else:
raise Exception, "Shouldn't be able to change const!"