Getting a set of lambda functions

Martin Manns mmanns at gmx.net
Mon May 26 17:11:25 EDT 2008


On Sun, 25 May 2008 18:46:27 -0700
John Nagle <nagle at animats.com> wrote:

> >>>> func_strings=['x', 'x+1', 'x+2', 'x']
> >>>> funclist = [eval('lambda x:' + func) for func in func_strings]
> 
>    What are you actually trying to do, anyway?  What's the
> application?
> 
>    You probably don't want to use "eval" that way.  If you want
> function objects out, use "compile".

I am writing on an application that I call pyspread
(http://pyspread.sourceforge.net).
It provides a grid (mapped to a numpy.array) into which users can type
in strings that contain python expressions.
Each expression is transformed into a function object in a second
numpy.array of the same size, so that each function can be called by
accessing the respective cell of the grid.

eval seems to work quite fine and provides nice access to globals,
system functions, modules, etc. Therefore, one can do general
programming tasks within the grid without worrying about cell
precedence.

compile returns code objects instead of function objects. I can of
course evaluate these code objects. However, when I store the code
objects, it is an extra operation each time I want to call the
function. So what is the benefit?

More specific: Is there any benefit of calling:

eval(compile(mystring, '', 'eval'))

instead of 

eval(mystring)

?

What are the drawbacks of my approach that I may be missing?
Any suggestions?

Best Regards

Martin



More information about the Python-list mailing list