473,491 Members | 2,008 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

Lisp-like macros in Python?


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.

Any comments and improvements are appreciated.

Regards,
Sturla Molden


__codestore__ = {}

def macro(func):

"""
Lisp-like macros in Python
(C) 2007 Sturla Molden

@macro decorates a function which must return a Python
expression
as a string. The expression will be evaluated in the context
(stack frame)
of the caller.
"""

def macro_decorator(*args,**kwargs):
global __codestore__
import sys
pycode = '(' + func(*args,**kwargs) + ')'
try:
ccode = __codestore__[pycode]
except:
ccode = compile(pycode,'macrostore','eval')
__codestore__[pycode] = ccode
frame = sys._getframe().f_back
try:
retval = eval(ccode,frame.f_globals,frame.f_locals)
return retval
except:
raise
macro_decorator.__doc__ = func.__doc__
return macro_decorator
# Usage example

def factorial(x):

""" computes the factorial function using macro expansion """

@macro
def fmacro(n):

""" returns '1' or 'x*(x-1)*(x-2)*...*(x-(x-1))' """

if n == 0:
code = '1'
else:
code = 'x'
for x in xrange(1,n):
code += '*(x-%d)' % (x)
return code

return fmacro(x)

May 1 '07 #1
5 2311
On May 1, 5:10 pm, sturlamolden <sturlamol...@yahoo.nowrote:
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.

May 1 '07 #2
Converge is a Python-style language with a macro facility. See
http://convergepl.org/

Pascal

--
My website: http://p-cos.net
Common Lisp Document Repository: http://cdr.eurolisp.org
Closer to MOP & ContextL: http://common-lisp.net/project/closer/
May 1 '07 #3
sturlamolden <st**********@yahoo.nowrites:
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.

Any comments and improvements are appreciated.

Regards,
Sturla Molden
I don't know python, but check out

http://www.cl-user.net/asp/libs/clpython

--
Duane Rettig du***@franz.com Franz Inc. http://www.franz.com/
555 12th St., Suite 1450 http://www.555citycenter.com/
Oakland, Ca. 94607 Phone: (510) 452-2000; Fax: (510) 452-0182
May 1 '07 #4
On May 1, 9:10 am, sturlamolden <sturlamol...@yahoo.nowrote:
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.
How about something that can't be done with a function, such as the
functionality of the "with" statement that was added to python 2.5?

Yes, it has to handle a suite of statements.

It would be nice if it handled both the "{as target}" and no target
forms.

Also, it shouldn't rely on magic names - if it needs a variable for
its purposes, it should guarantee that said variable and/or use can
not be one that affects how the rest of the user's program behaves.

There's a fair amount of relevant discussion in http://www.python.org/dev/peps/pep-0343/
..

May 1 '07 #5
Duane Rettig wrote:
sturlamolden <st**********@yahoo.nowrites:

>>Hello

The Lisp crowd always brags about their magical macros.
I used LISP back when LISP macros were popular.
You don't want to go there. It degrades readability
without improving the language.

Check out the original "MIT loop macro", used to put
something comparable to a FOR statement into early versions
of LISP.

http://www.cs.cmu.edu/afs/cs/project...oop/mit/0.html

Note that it's at version 829. And that was with MIT people fixing it.
That thing was a trouble spot for a decade or more.

Scheme added a "do" statement as part of the language, which
was the right answer. The "loop macro" was, at long last, retired
around 1991.

There are lots of "l33t" features one can put in a language,
but in the end, they're mostly not that helpful.

The people who advocate "l33t features" usually need to do more
maintenance programming on the code of others, to get more of a sense
of gives real, operational trouble in a programming language.
Really. After you've fixed the bad code of others, then you're
entitled to talk about language design.

As someone who's programmed in all too many languages and with
a background in formal proof systems, I would make few changes to
Python as a language. (And most of the things I'd change involve
removing less-used features that constrain implementations.)
The language is fine. The problems are elsewhere.
The CPython implementation is way too slow and some of the libraries
are flakey. That's what needs attention.

John Nagle
May 1 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

73
7892
by: RobertMaas | last post by:
After many years of using LISP, I'm taking a class in Java and finding the two roughly comparable in some ways and very different in other ways. Each has a decent size library of useful utilities...
303
17412
by: mike420 | last post by:
In the context of LATEX, some Pythonista asked what the big successes of Lisp were. I think there were at least three *big* successes. a. orbitz.com web site uses Lisp for algorithms, etc. b....
34
2642
by: nobody | last post by:
This article is posted at the request of C.W. Yang who asked me to detail my opinion of Lisp, and for the benefit of people like him, who may find themselves intrigued by this language. The...
82
5282
by: nobody | last post by:
Howdy, Mike! mikecoxlinux@yahoo.com (Mike Cox) wrote in message news:<3d6111f1.0402271647.c20aea3@posting.google.com>... > I'm a C++ programmer, and have to use lisp because I want to use >...
761
27978
by: Neo-LISPer | last post by:
Hey Recently, I researched using C++ for game programming and here is what I found: C++ game developers spend a lot of their time debugging corrupted memory. Few, if any, compilers offer...
1
2893
by: Ramza Brown | last post by:
Crazy, I know, but that is my question. Even google let me down: Anybody know of a lisp interpreter in php? And, I tried c.l.l. No dice. Even something similar. If you have worked with...
1
2690
by: Bore Biko | last post by:
In this time a new mostly languges (Java, C#), uses garbage collection, ant this was a one of faults of LISP in past times... The idea of Java virtual machine is totaly copy of LISP byte code...
10
1650
by: Bore Biko | last post by:
In this time a new mostly languges (Java, C#), uses garbage collection, ant this was a one of faults of LISP in past times... The idea of Java virtual machine is totaly copy of LISP byte code...
0
843
by: paddy3118 | last post by:
Hello, I have just expanded the Wikipedia stub article on docstrings at http://en.wikipedia.org/wiki/Docstring. Unfortunately I do not know about Lisp, but took the time to google and found a...
3
2266
by: Malcolm McLean | last post by:
I'm thinking of doing some of the high-level logic in my program in lisp. Is there an easy way to integrate lisp with C? At the moment my thoughts are moving along the lines of a cheap and...
0
6978
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7154
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6858
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7360
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5451
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4881
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
1392
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
633
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
280
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.