[Tutor] executing a string representing python code

Adam Pridgen atpridgen at mail.utexas.edu
Mon Mar 5 09:16:57 CET 2007


here's the magic you are looking for:

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)
f = locals()["some_func"]
print f("wasn't that cool!")

When you exec the str, it will create a function object, and then you
can obtain the object by accessing the object by kwd in the locals()
dictionary.  Guess it's not really magic, but I think it is still
pretty cool ;)  There also several variations to this method, but this
is the most readable IMHO.

Cheers,

Adam


On 3/2/07, Cecilia Alm <flickita at gmail.com> wrote:
> I know that there are several ways to execute a string which represents a
> piece of python code.
>  Out of curiosity, is it only eval which returns a value? (as below, where
> the string corresponds to a defined function).
>
>  >>> def addone(val):
>  ...     return val + 1
>  ...
>  >>> res = eval('addone(10)')
>
> Thanks!
>
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>


More information about the Tutor mailing list