Getting a set of lambda functions

Ivan Illarionov ivan.illarionov at gmail.com
Mon May 26 20:36:23 EDT 2008


On May 27, 1:11 am, Martin Manns <mma... at gmx.net> wrote:
> On Sun, 25 May 2008 18:46:27 -0700
>
> John Nagle <na... 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

Yes, there is.
Your original example can be rewritten

>>> func_strings=['x', 'x+1', 'x+2', 'x']
>>> funclist = [compile('lambda x: %s' % func, '<string>', 'eval') for func in func_strings]
>>> len(funclist)
4
>>> len(set(funclist))
3
>>> eval(funclist[0])(1)
1

Ivan



More information about the Python-list mailing list