In Python, any variable can be re-bound at will -- and modules don't let you define special methods such as an instance's __setattr__ to stop attribute re-binding. Easy solution (in Python 2.1 and up): use an instance as "module"...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# Put in const.py...: class _const: class ConstError(TypeError): pass def __setattr__(self,name,value): if self.__dict__.has_key(name): raise self.ConstError, "Can't rebind const(%s)"%name self.__dict__[name]=value import sys sys.modules[__name__]=_const() # that's all -- now any client-code can import const # and bind an attribute ONCE: const.magic = 23 # but NOT re-bind it: const.magic = 88 # raises const.ConstError # you may also want to add the obvious __delattr__
In Python 2.1 and up, no check is made any more to force entries in sys.modules to be actually module objects. You can install an instance object there and take advantage of its attribute-access special methods (e.g., as in this snippet, to prevent rebindings; probably more useful, to synthesize attributes on the fly in a __getattr__; whatever...), while still having client-code get the thing with "import whatever". You may also choose to see this as a more Pythonic 'singleton' pattern, or, rather, idiom:-) (but, regarding singleton, also see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531).