Returning a value from exec or a better solution
Jack Trades
jacktradespublic at gmail.com
Mon Aug 29 10:41:51 EDT 2011
I'm writing a Scheme interpreter and I need to be able to create and return
a Python function from a string.
This is a port of another Scheme interpreter I wrote in Scheme. What I'm
trying to do looked like this:
(define (scheme-syntax expr)
(hash-table-set! global-syntax (car expr) (eval (cadr expr))))
Where expr was of the form (symbol (lambda (exp) ...)). This added a new
special form handler.
I came up with a very ugly solution in Python:
def add_special_form_handler(expr):
exec(expr.cdr.car)
special_forms[expr.car] = f
Where expr.car = the symbol to be dispatched on and expr.cdr.car = a string
of Python code defining a function that must be named f.
I wanted to use an anonymous function here, but with the limitations of
Python's lambda that would probably make things more complicated. Failing
that I wanted to allow the user to manually return the function from the
string, like this:
a = exec("""
def double(x):
return x * 2
double
""")
However it seems that exec does not return a value as it produces a
SyntaxError whenever I try to assign it.
Is there a better way to do this?
--
Nick Zarczynski
Pointless Programming Blog <http://pointlessprogramming.wordpress.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110829/c235203c/attachment.html>
More information about the Python-list
mailing list