what is lambda used for in real code?

Adam DePrince adam at cognitcorp.com
Fri Dec 31 23:22:01 CET 2004

On Fri, 2004-12-31 at 01:53, Steven Bethard wrote:
> I thought it might be useful to put the recent lambda threads into 
> perspective a bit.  I was wondering what lambda gets used for in "real" 
> code, so I grepped my Python Lib directory.  Here are some of the ones I 
> looked, classified by how I would rewrite them (if I could):
<snipping wonderful verbosity>

> So, those are my thoughts on how lambdas are "really" used.  If others 
> out there have real-life code that uses lambdas in interesting ways, 
> feel free to share them here!

Lets not forget the "real reason" for lambda ... the elegance of
orthogonality.   Why treat functions differently than any other object? 

We can operate on every other class without having to involve the
namespace, why should functions be any different?  Wouldn't it to awful
if we had to write:

x = 3 * y ** 2 + 4 * y + 5 


a = 3 
e = 2 
b = 4
c = 5
x = a * y ** e + b * y + c

Everybody understand that sometimes a number just isn't important enough
to assign to the name space.  And we all can understand that this
applies to other data types, for example:

print "The answer is", x

Unless internationalization was a concern, few people would write:

THE_ANSWER_IS = "The answer is"
print THE_ANSWER_IS, x

But when we consider functions, we suddenly change.  Understandably we
have a certain bias towards functions.  When programming, the most
commonly constructed object is the function.  We likely spend more time
crafting function objects than any other object.  Our reflex to
economize on the programming process focuses on the reduction in
function code creation time, hence the a focus on reuseabiity and a
plethora of ways to categorize our code to achieve this end.  

The notion that we would use a function exactly once is almost blasphemy
to such a perspective.  But it is true ... there are times when a
programmer will want to construct and use a function in exactly one
place for one singular purpose.  In my own code, this occurs most often
when the function is used as a parameters to another function.  

Examples of this are the cmp parameters to [].sort.  The function I
provide to cmp is only barely more important to preserve for posterity
than the value I might provide to the same functions "reverse"

In sort, we must preserve the ability to create an anonymous function
simply because we can do so for every other object type, and functions
are not special enough to permit this special case.

Adam DePrince 

More information about the Python-list mailing list