<span class="gmail_quote"><br></span>Thanks, Adam. I guess the exec would be exec("some_func").<br>
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.<br>
<br>
>>> eval('some_func("wasn\'t that cool")')<br>
Hello World wasn't that cool<br>
'Done'<br>
<br>
in other words<br>
<br>
>>> s = eval('some_func("wasn\'t that cool")')<br>
Hello World wasn't that cool<br>
>>> s<br>
'Done'<br>
<br><br><div><span class="gmail_quote">2007/3/5, Adam Pridgen <<a href="mailto:atpridgen@mail.utexas.edu" target="_blank" onclick="return top.js.OpenExtLink(window,event,this)">atpridgen@mail.utexas.edu</a>>:</span>
<div><span class="e" id="q_1112287864bbda49_1"><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
here's the magic you are looking for:<br><br>func_str = \<br>'''<br>def some_func(value):<br># youwould check value instance here and do something to it<br> print "Hello World", value<br> return "Done"
<br>'''<br>exec(func_str)<br>f = locals()["some_func"]<br>print f("wasn't that cool!")<br><br>When you exec the str, it will create a function object, and then you<br>can obtain the object by accessing the object by kwd in the locals()
<br>dictionary. Guess it's not really magic, but I think it is still<br>pretty cool ;) There also several variations to this method, but this<br>is the most readable IMHO.<br><br>Cheers,<br><br>Adam<br><br><br>On 3/2/07, Cecilia Alm <
<a href="mailto:flickita@gmail.com" target="_blank" onclick="return top.js.OpenExtLink(window,event,this)">flickita@gmail.com</a>> wrote:<br>> I know that there are several ways to execute a string which represents a
<br>> piece of python code.<br>> Out of curiosity, is it only eval which returns a value? (as below, where
<br>> the string corresponds to a defined function).<br>><br>> >>> def addone(val):<br>> ... return val + 1<br>> ...<br>> >>> res = eval('addone(10)')<br>><br>> Thanks!
<br>><br>><br>><br>> _______________________________________________<br>> Tutor maillist - <a href="mailto:Tutor@python.org" target="_blank" onclick="return top.js.OpenExtLink(window,event,this)">Tutor@python.org
</a><br>> <a href="http://mail.python.org/mailman/listinfo/tutor" target="_blank" onclick="return top.js.OpenExtLink(window,event,this)">
http://mail.python.org/mailman/listinfo/tutor</a><br>><br>><br></blockquote></span></div></div><span class="sg"><br><br clear="all"><br>-- <br>E. Cecilia Alm<br>Graduate student, Dept. of Linguistics, UIUC<br>Office: 2013 Beckman Institute
</span><br clear="all"><br>-- <br>E. Cecilia Alm<br>Graduate student, Dept. of Linguistics, UIUC<br>Office: 2013 Beckman Institute