anonymous function with multiple statements

Yingjie Lan lanyjie at yahoo.com
Sun Jul 10 10:21:43 EDT 2011


Hi all, 

I wonder if Python provides a way to define anonymous functions containing 
multiple statements? With lambda form, we can only define a function of a single 
expression. In Javascript, it is possible to define 
a full-fledged anonymous functions, which suggests it is useful to have it. In 
Python, it might be like this:


#==============

def test( fn, K ): 
    return sum(fn(i) for i in range(K))/K

test( def (i): #indent from start of this line, not from 'def'
    from math import sin
    #the last statement ends with a ',' or ')'.
    return sin(i)+i*i;, 100) #';' to mark end of statement 

#another way:
test( def (i): #indent from start of this line, not from 'def'
    from math import sin
    return sin(i)+i*i
  , 100) #freely place ',' anywhere

#===============

Any thoughts?

Yingjie



More information about the Python-list mailing list