Returning a value from exec or a better solution
Rob Williscroft
rtw at rtw.me.uk
Tue Aug 30 03:28:41 EDT 2011
Jack Trades wrote in
news:CAG5udOh1+oE4g9Frjp3pucbHUtWcN34KK35a-Xs2YqkZH9X5=w at 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.
More information about the Python-list
mailing list