[Tutor] executing a string representing python code

Alan Gauld alan.gauld at btinternet.com
Mon Mar 5 18:14:28 CET 2007


"Cecilia Alm" <ebbaalm at uiuc.edu> wrote

> Thanks, Adam. I guess the exec would be exec("some_func").
> The result seems pretty similar to eval(), allthough eval() seems 
> more
> straight-forward if the aim is to assign the returned value ("Done") 
> to a
> variable.

>>>> s = eval('some_func("wasn\'t that cool")')
> Hello World wasn't that cool
>>>> s
> 'Done'

You should be able to just do:

>>> s = some_func("wasn't that cool")

The whole point of the exec is that the function now exists in
your local namespace. You can execute it as any other function.

>> func_str = \
>> '''
>> def some_func(value):
>> # youwould check value instance here and do something to it
>>     print "Hello World", value
>>     return "Done"
>> '''
>> exec(func_str)

This creates the function

>> f = locals()["some_func"]
>> print f("wasn't that cool!")

There should be no need for this trickery.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list