Returning a value from exec or a better solution

Jack Trades jacktradespublic at
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):
  special_forms[] = f

Where = the symbol to be dispatched on and = 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

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 <>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list