Returning a value from exec or a better solution
Rob Williscroft
rtw at rtw.me.uk
Tue Aug 30 03:37:37 EDT 2011
Jack Trades wrote in news:CAG5udOiOAge3uHrGSDTZ412GAg+CC-
6u8iGOyJ0Lnf3HnwUVzA at mail.gmail.com in gmane.comp.python.general:
>> >>> 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
>>
>
> That's brilliant and works flawlessly. Thank you very much!
If an impementation (as you say up thread) can populate globals
or locals with whatever they want, then how do you know that last
item added was the function definition the user supplied ?
Rob.
More information about the Python-list
mailing list