Returning a value from exec or a better solution

Arnaud Delobelle arnodel at gmail.com
Mon Aug 29 18:50:46 EDT 2011


On 29 August 2011 23:14, Jack Trades <jacktradespublic at gmail.com> wrote:
> 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).

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



More information about the Python-list mailing list