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


Groups > comp.lang.python > #12429

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-30 07:28 +0000
References <CAG5udOg=GtFGPmTB=1OJNvNRPdYUcxDoKN1WJQMOMv9gx0+fZA@mail.gmail.com> <Xns9F50BCB7B5708rtwfreenetREMOVEcouk@80.91.229.10> <CAG5udOh1+oE4g9Frjp3pucbHUtWcN34KK35a-Xs2YqkZH9X5=w@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.564.1314689337.27778.python-list@python.org> (permalink)

Show all headers | View raw


Jack Trades wrote in
news:CAG5udOh1+oE4g9Frjp3pucbHUtWcN34KK35a-Xs2YqkZH9X5=w@mail.gmail.com
in gmane.comp.python.general: 

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

Why not just get the name from the user, or use a regular expression
to extract the first (or last, maybe) definition from the source string.

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-30 07:28 +0000

csiph-web