Python Global Constant

Greg Ewing (using news.cis.dfn.de) g2h5dqi002 at sneakemail.com
Thu Jul 10 00:06:55 EDT 2003


Peter Hansen wrote:
> Just do what you did above, without the "const" modifier, which
> doesn't exist and is not really needed in Python.

If you *really* insist on preventing anyone from changing
them, it is possible, with some hackery. Here's one way
that works:

#######################################################
#
#  MyModule.py
#

_constants = ['PI', 'FortyTwo']

PI = 3.1415
FortyTwo = 42

import types

class _ConstModule(types.ModuleType):

   __slots__ = []

   def __setattr__(self, name, value):
     if name in self.__dict__['_constants']:
       raise ValueError("%s is read-only" % name)
     self.__dict__[name] = value

del types
import MyModule
MyModule.__class__ = _ConstModule

#######################################################

Figuring out *how* it works is left as an exercise
for the student. :-)

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg





More information about the Python-list mailing list