C macros in Python.
Alex Martelli
aleaxit at yahoo.com
Wed Oct 18 03:55:13 EDT 2000
"Quinn Dunkan" <quinn at zloty.ugcs.caltech.edu> wrote in message
news:slrn8updfp.ero.quinn at zloty.ugcs.caltech.edu...
> On Tue, 17 Oct 2000 11:30:35 +0100, Burkhard Kloss <bk at xk7.com> wrote:
> >> On a different, but related, topic...I sometimes miss C's #define
> >> macro. There doesn't seem to be any similar thing in Python capable of
> >> creating identifiers which are 1) constant, that is, "read only", and
2)
> >> truly global in scope.
> >How about defining a function that returns the value? that would make it
> >nicely read-only.
> >
> >define pi(): return 3.14....
>
> pi = 3
>
> will defeat that nicely.
>
> If you want something to be constant in python, don't reassign it. Not
that
> hard, now is it? :) And if you want something "truly global" you could
shove
> it into __builtins__, which is great not only for confusing other people
but
> also increasing job security. And that's why you want globals in the
first
> place, right? :)
I think the "truly global in scope" can indeed be obtained by the
shove-into-__builtins__ approach, and accidental modifications could
be stopped by having a dot in the name...:
>>> const.define('pi', 3.1415926)
>>> const.pi
3.1415926
>>> const.pi = 3
<some exception...>
__builtin__.const would obviously have to be an instance of some
suitable class (which you could put in place in your site.py), e.g.:
In site.py, or wherever...:
class Const:
def define(self, name, value):
if self.__dict__.has_key(name):
raise KeyError, "Can't redefine constant %s"%name
self.__dict__[name] = value
def __setattr__(self, name,value):
if self.__dict__.has_key(name):
raise KeyError, "Can't redefine constant %s"%name
raise KeyError, "Use const.define to define constants"
import __builtin__
__builtin__.const = Const()
Of course, we might not want this specific separation of
define and __setattr__ -- it's just one of several roughly
equivalent possibilities. Anyway, with this design...:
>>> const.define('pi',3.1415962)
>>> print const.pi
3.1415962
>>> const.pi = 3
Traceback (innermost last):
File "<pyshell#32>", line 1, in ?
const.pi = 3
File "<pyshell#23>", line 8, in __setattr__
raise KeyError, "Can't redefine constant %s"%name
KeyError: Can't redefine constant pi
>>>
Of course, it IS possible for an errant client-code module
to import __builtin__ then set __builtin__.const to refer
to some other object, but I would not particularly worry
about this happening by accident:-).
Alex
More information about the Python-list
mailing list