Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #12408

Re: Returning a value from exec or a better solution

From Rob Williscroft <rtw@rtw.me.uk>
Subject Re: Returning a value from exec or a better solution
Date 2011-08-29 17:30 +0000
References <CAG5udOg=GtFGPmTB=1OJNvNRPdYUcxDoKN1WJQMOMv9gx0+fZA@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.547.1314639069.27778.python-list@python.org> (permalink)

Show all headers | View raw


Jack Trades wrote in
news:CAG5udOg=GtFGPmTB=1OJNvNRPdYUcxDoKN1WJQMOMv9gx0+fZA@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.

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Returning a value from exec or a better solution Rob Williscroft <rtw@rtw.me.uk> - 2011-08-29 17:30 +0000

csiph-web