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 <[EMAIL PROTECTED]>:
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 < [EMAIL PROTECTED]> 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 - [email protected]
> 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
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor