Returning a value from exec or a better solution

Rob Williscroft rtw at rtw.me.uk
Mon Aug 29 13:30:53 EDT 2011


Jack Trades wrote in
news:CAG5udOg=GtFGPmTB=1OJNvNRPdYUcxDoKN1WJQMOMv9gx0+fZA at mail.gmail.com
in gmane.comp.python.general: 

> ... 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.

def test():
  src = (
      "def double(x):"
      "  return x * 2"
    )
  globals  = {}
  exec( src, globals )
  return globals[ "double" ]
  
print( test() )

The a bove works on 2.7 (I tested it) on earlier versions you may need 
to use:

    	exec src in globals 

Rob.




More information about the Python-list mailing list