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 - Tutor@python.org > http://mail.python.org/mailman/listinfo/tutor > > _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor