Returning a value from exec or a better solution
jacktradespublic at gmail.com
Mon Aug 29 16:41:51 CEST 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:
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("""
return x * 2
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?
Pointless Programming Blog <http://pointlessprogramming.wordpress.com>
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list