If Python had a macro facility similar to Lisp/Scheme (something like MetaPython), how would you use it?
If you are a Lisp/Scheme programmer, what sorts of things do y
Some examples of lisp macros:
This is a somewhat late answer, but MacroPy is a new project of mine to bring macros to Python. We have a pretty substantial list of demos, all of which are use cases which require macros to implement, for example providing an extremely concise way of declaring classes:
@case
class Point(x, y)
p = Point(1, 2)
print p.x # 1
print p # Point(1, 2)
MacroPy has been used to implement features such as:
Check out the linked page to find out more; I think I can confidently say that the use cases we demonstrate far surpass anything anyone's suggested so far on this thread =D
In lisp, macros are just another way to abstract ideas.
This is an example from an incomplete ray-tracer written in clojure:
(defmacro per-pixel
"Macro.
Excecutes body for every pixel. Binds i and j to the current pixel coord."
[i j & body]
`(dotimes [~i @width]
(dotimes [~j @height]
~@body)))
If you want to do something to every pixel with coordinates (i,j), say, draw a black pixel if i is even, you would write:
(per-pixel i,j
(if (even? i)
(draw-black i,j)))
This is not possible to do without macros because @body can mean anything inside (per-pixel i j @body)
Something like this would be possible in python as well. You need to use decorators. You can't do everything you can do with lisp macros, but they are very powerful
Check out this decorator tutorial: http://www.artima.com/weblogs/viewpost.jsp?thread=240808
Well, I'd like instead of
print >> sys.stderr, "abc"
to write
err "abc"
in some scripts which have many debug printout statements.
I can do
import sys
err = sys.stderr
and then
print >> err, "abc"
which is shorter, but that still takes too many characters on the line.
Here's one real-world example I came across that would be trivial with macros or real metaprogramming support, but has to be done with CPython bytecode manipulation due to absence of both in Python:
http://www.aminus.net/dejavu/chrome/common/doc/2.0a/html/intro.html#cpython
This is how the problem is solved in Common Lisp using a combination of regular macros, and read-macros to extend the syntax (it could have been done without the latter, but not the former):
http://clsql.b9.com/manual/csql-find.html
The same problem solved in Smalltalk using closures and metaprogramming (Smalltalk is one of the few single-dispatch OO languages that actually gets message passing right):
http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg02096.html
Here I tried to implement the Smalltalk approach in Common Lisp, which is a good illustration of how metaprogramming is poorly supported in the latter:
http://carcaddar.blogspot.com/2009/04/closure-oriented-metaprogramming-via.html