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


Groups > comp.lang.python > #12423

Re: Returning a value from exec or a better solution

References <CAG5udOg=GtFGPmTB=1OJNvNRPdYUcxDoKN1WJQMOMv9gx0+fZA@mail.gmail.com> <Xns9F50BCB7B5708rtwfreenetREMOVEcouk@80.91.229.10> <CAG5udOh1+oE4g9Frjp3pucbHUtWcN34KK35a-Xs2YqkZH9X5=w@mail.gmail.com>
Date 2011-08-29 23:50 +0100
Subject Re: Returning a value from exec or a better solution
From Arnaud Delobelle <arnodel@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.559.1314658248.27778.python-list@python.org> (permalink)

Show all headers | View raw


On 29 August 2011 23:14, Jack Trades <jacktradespublic@gmail.com> wrote:
> On Mon, Aug 29, 2011 at 12:30 PM, Rob Williscroft <rtw@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).

Hi Jack,

Here is a possible solution for your problem (Python 3):


>>> class CapturingDict(dict):
...     def __setitem__(self, key, val):
...         self.key, self.val = key, val
...         dict.__setitem__(self, key, val)
...
>>> c = CapturingDict()
>>> exec("def myfunction(x): return 1", c)
>>> c.key
'myfunction'
>>> c.val
<function myfunction at 0x100634d10>

HTH,

-- 
Arnaud

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


Thread

Re: Returning a value from exec or a better solution Arnaud Delobelle <arnodel@gmail.com> - 2011-08-29 23:50 +0100

csiph-web