[SciPy-User] Avoiding lambda functions

Robert Kern robert.kern@gmail....
Mon Oct 18 13:25:11 CDT 2010


On Mon, Oct 18, 2010 at 13:11, David MacQuigg <macquigg@ece.arizona.edu> wrote:
> 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:
> <pre>
> 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
> </pre>
> 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.

Not at all. The first version is calling the lambda inside the
gaussianfilter() function for some weird reason. Check the
parentheses. Your version defines the function (incorrectly, as it
happens), but does not call it. The least-confusing version is this:

def gaussianfilter(sigma, shape):
    iray,jray  = indices(shape)
    filter = gauss(iray, jray, sigma, shape)
    return filter

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco


More information about the SciPy-User mailing list