Finally found a use for lambda!

Hannu Kankaanpää hanzspam at yahoo.com.au
Mon Sep 15 04:33:06 EDT 2003


Roy Smith <roy at panix.com> wrote in message news:<roy-FFBAC5.22283914092003 at reader2.panix.com>...
> My apologies for a somewhat silly posting, but after 6 years of hacking 
> Python, I finally found a use for lambda!  I wanted to write a unit test 
> to prove that a given dictionary does not have a given key.  Since 
> assertRaises requires its second argument to be something callable, 
> instead of writing:
> 
>         self.assertRaises (KeyError, foo['bar'])
> 
> I had to write:
> 
>         self.assertRaises (KeyError, lambda: foo['bar'])
> 
> Of course, now that I think about it, I could have also written:
> 
>         self.assertEqual (foo.has_key ('bar')), 0)
> 
> so I guess I didn't really need the lambda after all :-)

Lambda is pretty useless in Python, unfortunately. List comprehensions
reduce their uses with filter and map, and any more complex closure
has to be written as a named function anyway.. I wish lambda would
allow statements in them also, so I could do

func(lambda x: arr[x] = y)

Little closures like that are sometimes handy. But having to do

def fn(x): arr[x] = y
func(fn)

is not too much of a burden. Lambda would be just nicer.
The current use I've had for lambda has been similar to yours. I
wanted a separate thread to initialize something in a class on
the background, so I did something like

threading.Thread(target=lambda: self.doSomething(a, b, c)).start()

I think I've used it elsewhere too but I don't have my sources
here.




More information about the Python-list mailing list