[Tutor] Fwd: executing a string representing python code

Cecilia Alm ebbaalm at uiuc.edu
Mon Mar 5 15:37:21 CET 2007


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.

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

in other words

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


2007/3/5, Adam Pridgen <atpridgen at mail.utexas.edu>:
>
> 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
> >
> >
>



-- 
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute

-- 
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070305/a6b984ec/attachment.htm 


More information about the Tutor mailing list