RFC -- Hygienic Macros in Python
phil hunt
philh at comuno.freeserve.co.uk
Sat Feb 9 19:31:40 EST 2002
On Fri, 8 Feb 2002 23:04:57 -0600, Jason Orendorff <jason at jorendorff.com> wrote:
>phil hunt wrote:
>> Python macros should, if they exist, have a superset of the
>> capabilities of
>> C macros. Including the ability to be replaced by arbitrary code in the
>> program. Why arbitrary? firstly, because it is conceptually simple;
>> secondly because it doesn't restrict the programmer.
>
>C macros are quite restrictive, precisely *because* they simply
>paste tokens into your program.
>
>> Consider this code:
>>
>> defmacro incj:
>> j = j + 1
>
>Well, I don't think that's particularly realistic code.
Nor do I, particularly. I can't offhand think of anything where I'd
particularly want to use macros in Python, except perhaps to define my
own control structures.
But just cos i can't think of it, doesn't mean someone else won't
find it useful.
> Consider
>this instead.
>
>Jason Orendorff wrote:
>> defmacro synchronized(lock_expr, code_block):
>> lock = ^lock_expr
>> lock.acquire()
>> try:
>> ^code_block
>> finally:
>> lock.release()
>
>Under a non-hygienic macro system, obviously I wouldn't write it
>like that because "lock" might clash with a local name. Indeed if
>I have nested "synchronized" statements it's guaranteed to clash.
>So what should the code look like in a non-hygienic system?
The way i would do it, if I was implementing it, would be something
like:
defmacro synchronized(lock_expr, code_block):
local lock
lock = ^lock_expr
lock.acquire()
try:
^code_block
finally:
lock.release()
Where the "local lock" declaration means something like: in the
current namespace create a local variable name that doesn't clash with
anything else.
In something like C++ you could just put {...} round it can define
variables within that and they'd be local to it, but you can't do
that in Python.
--
===== Philip Hunt ===== philh at comuno.freeserve.co.uk =====
Herbivore, a zero-effort email encryption system. Details at:
<http://www.vision25.demon.co.uk/oss/herbivore/intro.html>
More information about the Python-list
mailing list