macro FAQ

Michele Simionato mis6 at pitt.edu
Sun Aug 24 05:03:14 EDT 2003


Jacek Generowicz <jacek.generowicz at cern.ch> wrote in message news:<tyfbruf998w.fsf at lxplus014.cern.ch>...
> ==== Example 1: a debugging aid ================================
> 
> One litte macro I have for debugging purposes (let's call it "show"),
> allows me to print out the source code of a number of expressions,
> along with their values. At this point, note that Python's horribly
> irregular syntax <0.5 wink> already starts causing problems: should
> the macro look like a block of code, or should it look like a function
> call; in Lisp both look identical.
> 
> The "block" version of the show macro invocation:
> 
>     show:
>         sin(x)
>         a
>         a + b + c
> 
> The "function" version of the show macro invocation:
> 
>     show(sin(x), a, a + b + c)
> 
> In both cases, the action of the macro should be to replace itself
> with its expansion, _before_ the compiler gets to see the source code.
> The expansion should look like this:
> 
>     print "sin(x) =>", sin(x)
>     print "a =>", a
>     print "a + b + c =>", a + b + c
> 
> Note the key points:
> 
> 1) The macro receives some data, and transforms it into valid Python
>    source code
> 
> 2) This happens before compile time
> 
> 3) Nothing "outside" the macro call gets affected by the macro's
>    action.
> 
> Can this be implemented using metaclasses, or any other existing
> Python mechanism ?

Yes.

http://groups.google.it/groups?hl=it&lr=&ie=UTF-8&threadm=2259b0e2.0306040808.1d737a54%40posting.google.com&rnum=2&prev=/groups%3Fhl%3Dit%26lr%3D%26ie%3DISO-8859-1%26q%3Dsimionato%2Bmacros%26meta%3Dgroup%253Dcomp.lang.python.*

At the end it uses metaclasses+exec+a simple argument parser based on 
tokenize. EXPERIMENTAL code, which I would not trust except as proof
of concept.

> === Example 2: Alexander Schmolck's updating classes ===============

I think this also can be done with metaclasses (somebody already
posted a recipe in some other thread, Diederich?)

Michele Simionato, Ph. D.
MicheleSimionato at libero.it
http://www.phyast.pitt.edu/~micheles
--- Currently looking for a job ---




More information about the Python-list mailing list