Returning a value from exec or a better solution

Jack Trades jacktradespublic at gmail.com
Tue Aug 30 00:14:11 CEST 2011


On Mon, Aug 29, 2011 at 12:30 PM, Rob Williscroft <rtw at rtw.me.uk> wrote:

> Jack Trades wrote in
> > ... 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() )
>

I looked into doing it that way but it still requires that the user use a
specific name for the function they are defining.  The docs on exec say that
an implementation may populate globals or locals with whatever they want so
that also rules out doing a simple "for item in globals", as there may be
more than just the one function in there (though I suppose I may be able to
work around that).

-- 
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/ea64a16d/attachment.html>


More information about the Python-list mailing list