Over a million developers have joined DZone.

Constants In Python

·
From Alex's recipe.

# 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

Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}