DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Constants In Python

09.18.2005
| 8731 views |
  • submit to reddit
        From Alex's <a href=http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65207>recipe</a>.
# 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
const.magic = 23     # bind an attribute ONCE
const.magic = 88     # raises const.ConstError if re-bind