Finally found a use for lambda!

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Sep 15 04:46:09 EDT 2003


Roy Smith <roy at panix.com> wrote in 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'])
> 

Pretty much the same idea hit me a few weeks ago. Even when the argument is 
callable with arguments, using lambda here makes the test read more clearly 
than you get without.

I think you should submit a change request to the documentation for 
assertRaises/failUnlessRaises that would add another paragraph pointing out 
that using a lambda for the callable expression allows any expression to be 
tested to be written inline.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list