Lisp-like macros in Python?

Chris Russell christopher.m.russell at gmail.com
Tue May 1 13:59:14 EDT 2007


On May 1, 5:10 pm, sturlamolden <sturlamol... at yahoo.no> wrote:
> Hello
>
> The Lisp crowd always brags about their magical macros. I was
> wondering if it is possible to emulate some of the functionality in
> Python using a function decorator that evals Python code in the stack
> frame of the caller. The macro would then return a Python expression
> as a string. Granted, I know more Python than Lisp, so it may not work
> exactly as you expect.

The 'magical macros' of lisp are executed at compile time, allowing
arbitrary code transformations without the loss of run time
efficiency. If you want to hack this together in python you should
write a preprocessor that allows python code *to be run in future*
inter spaced with python code *to be executed immediately* and
replaces the executed code with it's output. The immediately executed
code should be able to make use of any existing code or definitions
that are marked as to be compiled in the future.

This is should be quite do-able in python(I think I haven't really
looked at it) because it has a REPL and everything that implies, but
you'd have to implement lispy macros as some kind of def_with_macros
which immediately produces a string which is equivalent to the macro
expanded function definition and then evaluates it.

Good luck in doing anything useful with these macros in a language
with non-uniform syntax however.




More information about the Python-list mailing list