Finally found a use for lambda!

Peter Otten __peter__ at
Mon Sep 15 09:18:45 CEST 2003

Roy Smith wrote:

> 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)

This is not strictly equivalent, i. e. for a custom dictionary you should
perform both tests. If assertEqual() is sufficient, then how about 

self.failIf("bar" in foo)

which seems as explicit as you can get without using plain english.

> so I guess I didn't really need the lambda after all :-)

Same goes for me since I converted from map() to list comprehensions.


More information about the Python-list mailing list