Python Global Constant

Jp Calderone exarkun at twistedmatrix.com
Thu Jul 10 02:01:47 EDT 2003


On Thu, Jul 10, 2003 at 04:06:55PM +1200, Greg Ewing (using news.cis.dfn.de) wrote:
> 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
> 

    >>> import MyModule
    >>> del MyModule._constants[:]
    >>> MyModule.PI = 'Cherry, please'
    >>> MyModule.PI
    'Cherry, please'

  Jp

-- 
"The problem is, of course, that not only is economics bankrupt but it has
 always been nothing more than politics in disguise ... economics is a form
 of brain damage."  -- Hazel Henderson





More information about the Python-list mailing list