No macros in Python

Beni Cherniavsky cben at techunix.technion.ac.il
Sun Dec 15 18:46:08 EST 2002


On 2002-12-15, Courageous wrote:

> I'd be happy with an easy mechanism to make a "macro function" that
> otherwise had the exact syntax of a function, but took its local
> namespace from the function in which it is invoked. I haven't thought
> very deeply about what this would mean, but I'm thinking a form of
> closure masquerading as a function definition.
>
Hmm, that's called "unhygienic macros" and is widely considered a bad
idea.  It breaks the encapsulation of the naming of local variables to one
function.  Magic will start/stop happening if one renames the arguments in
the function calling the macro.  The most evil macro bugs stem from the
macro allocating a variable (for its private use) in the calling function
in a way that clashes with the macro.

The opposite, "hygienic" macros are much more complex to implement.  The
point is to guarantee that code produced by the macro doesn't use any
names of the macro caller's namespace except those that are expclicitly
given to it.  This saves you from a lot of mistakes.  However, ensuring
the hygiene is almost impossible under LISP's powerfull approach of macros
being arbitrary functions generating code.  So Scheme devised a powerfull
language that can't describe non-hygienic macros -- but many people find
it too restrictive.

My current idea is that if you need to allocate state for the macro, an
object should be created and all non-hygienic things one wants to do
should be on attributes of the object.  Example (ignore the syntax):

usemacro i = myfor(range(10)):
    print i.value
    if i.value == 7:
        i.mybreak()

I also thought on having an operator to turn a local variable into a
property e.g. ``myfor(@i, range(10))`` but that would encourage a
call-by-reference style all around...

-- 
Beni Cherniavsky <cben at tx.technion.ac.il>





More information about the Python-list mailing list