ActiveState Code

Recipe 65207: Constants in Python


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"...

Python
 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__

Discussion

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).

Comments

  1. 1. At 3:05 p.m. on 25 oct 2001, philip nunez said:

    good for typechecking too?

    class typecheck:
        def __init__(self,i):
            self.__type__ = type(i)
        def __setattr__(self,name,value):
            if (name.find('__type__') != 0) and (type(value) != self.__type__):
                raise TypeError, "(%s) is not %s"%(name,self.__type__.__name__)
            self.__dict__[name]=value
    
    
    if __name__ == '__main__':
        import sys
        try:
            my_int = typecheck(1)
            my_int.x = 3
            my_int.y = 4
            my_int.z = 5
            my_int.h = 'hey'
        except:
            print sys.exc_type, sys.exc_value
    
        try:
            my_string = typecheck('')
            my_int.s = 'hello'
            my_int.t = 'byebye'
            my_int.u = 3
        except:
            print sys.exc_type, sys.exc_value
    
  2. 2. At 3:24 p.m. on 7 jan 2002, Jason Orendorff said:

    Don't get carried away, though. This is clever, but keep in mind that all the standard modules implement constants this way:

    AUDIO_FILE_MAGIC = 0x2e736e64
    AUDIO_FILE_ENCODING_MULAW_8 = 1
    AUDIO_FILE_ENCODING_LINEAR_8 = 2
    AUDIO_FILE_ENCODING_LINEAR_16 = 3
    

    This is much clearer to me. (It runs faster, too.)

  3. 3. At 8:43 a.m. on 28 apr 2005, Michael Shepanski said:

    Jason Orendorff, What prevents someone from re-declaring your variables?

  4. 4. At 1:19 a.m. on 30 jun 2005, marijn haverbeke said:

    The fact that they are all-uppercase and that the programmer knows that means they are intended to be constants.

    If the programmer is a moron, you're screwed anyway. I find all this tendency to try and create libraries/frameworks/utils that can not possibly be used incorrectly a little wrong-headed. Just follow conventions, document, and hope for the best.

  5. 5. At 6:27 p.m. on 2 oct 2005, Stephen Chappell said:

    except: Just make sure that you don't follow that philosophy when you are creating your end product. Your end-user should be able to crash the product. They should, instead, get warnings, if anything.

  6. 6. At 1:49 p.m. on 5 jun 2007, Thomas Ahle said:

    Good philosophy. This philosophy is the reason I like python. No need for restrictive private functions and stuff. It should be clear to people that this function is not supposed to be called, but if they REALLY want to, they can do it. And yes, this has nothing to do with the end user, which should of course be protected against h(im|er)self.

  7. 7. At 1:22 a.m. on 20 may 2008, chris skoni said:

    Error after running the module. After typing at prompt >>> : import const I get this error: Traceback (most recent call last): File "", line 1, in -toplevel- import const ImportError: No module named const

    I also tried >>> import _const (because definition has _const (not const)) - but the same error.

    So how does it work ?

    THIS IS THE CODE that I RAN: 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()

    -thanks-cs-

  8. 8. At 12:02 p.m. on 1 oct 2008, dharkness said:

    Did you create a file called const.py containing lines 2 through 9, inclusive? Did you place the file somewhere where the import would see it?

Sign in to comment