New statement proposal for Python

Alex Martelli aleaxit at yahoo.com
Thu Jun 14 15:43:08 EDT 2001


"David LeBlanc" <whisper at oz.nospamnet> wrote in message
news:9gao5s$8ft$7 at 216.39.170.247...
> One thing that bugs me about Python is that there's no really good way to
> have named constants so that magic numbers can be avoided. Assigning to a
> variable that (should) never changes is not the same (i.e. the "should
> never" part).

It's pretty easy to ensure that an exception is raised when an
attribute of a given module is re-bound -- all it takes is for
that module to NOT be a module, but rather an instance.

Put in const.py...:
:: start
class ConstError(TypeError):
    pass
class _const:
    def __setattr__(self,name,value):
        if self.__dict__.has_key(name):
            raise ConstError, "Can't rebind const(%s)"%name
        self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()
sys.modules[__name__].ConstError = ConstError
:: finis

That's it.  Now any module can:
    import const
and names can be bound ONCE in const:
    const.magic = 23
but NOT twice:
    const.magic = 42    # raises a const.ConstError

This doesn't give you an 'alias' that's actually an arbitrary
string of code, and as written still lets you explicitly
    del const.magic
    const.magic = 88
though it would suffice to add __delattr__ to impede
that, of course.  But I think it's sufficient, anyway.

Hmmm, maybe I should add that to the Cookbook... it
seems a little-known technique.  I think it only works in
Python 2.1, btw.  [Done -- not approved yet, but it's at
http://aspn.activestate.com/ASPN/Python/Cookbook/Recipe/65207
and I think it's already generally-visible].


Alex






More information about the Python-list mailing list