Is this a good use for lambda

Steven Bethard steven.bethard at gmail.com
Sat Dec 18 01:44:12 CET 2004


Harlin Seritt wrote:
> Charlie Taylor wrote:
> 
> 
>>I find that I use lambda functions mainly for callbacks to things like
>>integration or root finding routines as follows.
>>
>>flow = integrate(lambda x: 2.0*pi * d(x)* v(x) * sin(a(x)),xBeg, xEnd)
>>
>>root = findRoot(xBeg, xEnd,
>>       lambda x: y2+ lp*(x-x2) -wallFunc( x )[0], tolerance=1.0E-15)
>>
>>I have tried using named functions instead of using lambda functions,
>>however, I always end up with a convoluted, hard to follow mess.
>>
>>Is there a better solution than a lambda in the above situations?
> 
> 
> Yes. Write a separate function for it. It may actually take less time and be
> a good deal more readable. Also, you'll be able to call this mess again if
> you need to. :-)

Well, I think the jury could still be out on which version is more 
readable, but I don't understand the comment "I have tried using named 
functions instead of using lambda functions, however, I always end up 
with a convoluted, hard to follow mess."  If you know that:

<name> = lambda *args, **kwds: <expr>

is eqivalent to:

def <name>(*args, **kwds):
     return <expr>

then it's quite straightforward to translate from one to the other.  As 
an illustration, here are your functions translated from lambdas to defs:

def flowfunc(x):
     return 2.0*pi * d(x)* v(x) * sin(a(x))
flow = integrate(flowfunc, xBeg, xEnd)

def rootfunc(x):
     return y2 + lp*(x - x2) - wallFunc(x)[0]
root = findRoot(xBeg, xEnd, rootfunc, tolerance=1.0E-15)

I'm not necessarily suggesting that this is the right answer for your 
situation, just that the translation from lambda to def should be 
relatively simple if you decide that that's what you want to do.

Steve



More information about the Python-list mailing list