[SciPy-User] Avoiding lambda functions

David MacQuigg macquigg@ece.arizona....
Mon Oct 18 13:11:53 CDT 2010

I'm working on some Python examples to present to freshman students interested
science and engineering.  One of the more powerful examples is image processing
using FFTs and spatial filters.  The examples I have from a graduate class in
astronomy use lambda functions in a way which freshmen will find confusing.

Here is part of the example code:
from numpy import exp, indices  # numpy package from scipy.org
img0 = imread('Lena.pgm')    # a 200 by 200 greyscale image
shape = img0.shape           # (200, 200)

def gauss(i,j,sigma,shape):  # a 2D gaussian function
    x = -1.0 + 2.0*i/shape[0]
    y = -1.0 + 2.0*j/shape[1]
    ans = exp(-(x*x+y*y)/(2*sigma*sigma))
    return ans

def gaussianfilter(sigma,shape):
    iray, jray = indices(shape)     # indices for a 200 x 200 array
    filter = (lambda i,j: gauss(i,j,sigma,shape))(iray, jray)
    return filter

filter = gaussianfilter(0.1,shape)

This use of lambda is confusing.  The reason to use lambda syntax is that it
saves having to provide a name for a simple one-line function.  Here, we are
giving the lambda a name "filter", so there is no savings, just convoluted code,
which is contrary to the spirit of Python.

Let's try to "unconvolute" the gaussianfilter function.

def gaussianfilter01(sigma, shape):
    iray,jray  = indices(shape)
    def filter(i, j):
        return gauss(i,j,sigma,shape)(iray, jray)
    return filter
This doesn't work!! The problem is that the original function returns a numpy
array, and here we get just an ordinary function.  It seems that numpy is doing
something special with the lambda syntax.

How can we do this and keep it simple.  I would really like to avoid lambda
functions entirely, but not if it means we lose the elegance of numpy arrays.

More information about the SciPy-User mailing list