Python Macros

Paul Boddie paul at boddie.org.uk
Wed Oct 6 05:42:17 EDT 2004


Jeff Shannon <jeff at ccvcorp.com> wrote in message news:<10m6f8rbqe4h232 at corp.supernews.com>...
> 
> Often, someone wants to use a particular syntax feature out of 
> familiarity, rather than because it's really the best fit for the job at 
> hand.  This is particularly true when coming to a new language; one 
> naturally wants to continue programming in the style of the language(s) 
> one already knows, but that style may be completely inappropriate for 
> the new language.  Others have shown you how to force Python into the 
> style that you're used to; I'm suggesting alternative styles that will 
> fit better with the way that Python normally works.  It's almost always 
> better to use Python idioms when coding in Python, Scheme idioms when 
> coding in Scheme, and Java idioms when coding in Java, than it is to try 
> to write Python using Scheme idioms.

I've not been following this thread, so some of my comments may be a
bit out of context, but I can imagine using macros for situations
where I don't want to emulate some other language's syntax or
conventions. Here's an example:

I wrote a wrapper about the libxml2 module [1] in order to expose a
traditional DOM-style API. However, the wrapper introduces an overhead
which would make programs which use lots of classic DOM-style
operations run much slower than without the wrapper (almost to the
point of being as slow as other Python DOM packages). Now I don't
really care about the performance of DOM-intensive programs because
I'm using the wrapper as a convenient means of editing documents
before libxslt processes them, but given that libxml2 is one of the
faster DOM implementations, it would be nice to retain that
performance whilst exposing a more conventional API.

Now, if Python had macros (and I mean macros in the sense that Lisp
people presumably mean macros) I could write DOM-style code and have
that transformed to libxml2-style code before runtime. The only issue
with such a suggestion is that for this to happen automatically, some
awareness of object types is necessary before runtime by the
macro/transformation engine, but even if this is difficult in the
general case, I still believe that some kind of limited type inference
system could make it possible.

Paul

[1] http://www.python.org/pypi?%3Aaction=search&name=libxml2dom



More information about the Python-list mailing list