473,320 Members | 2,202 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Finally found a use for lambda!

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 :-)
Jul 18 '05 #1
9 2617
> [Roy Smith]
My apologies for a somewhat silly posting, but after 6 years of hacking
Python, I finally found a use for lambda!
Not silly at all! Besides in copying example GUI code I have never
found one either.
...
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 :-)


But the lambda version looks so much clearer, and it puts more
emphasis on the KeyError.

And I see you also practice the wonderful elegance of using 0 instead
of False. Booleans?!? Off with their heads!
Jul 18 '05 #2
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.

Peter
Jul 18 '05 #3
Roy Smith <ro*@panix.com> wrote in message news:<ro***********************@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.
Jul 18 '05 #4
Roy Smith <ro*@panix.com> wrote in news:roy-
FF*******************@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 du****@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?
Jul 18 '05 #5
> Of course, now that I think about it, I could have also written:
self.assertEqual (foo.has_key ('bar')), 0)


ObMinimalism attempt:

self.failIf(foo.has_key('bar'))
Jul 18 '05 #6
On Mon, Sep 15, 2003 at 01:33:06AM -0700, Hannu Kankaanp?? wrote:
Roy Smith <ro*@panix.com> wrote in message news:<ro***********************@reader2.panix.com> ...

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)


Well, you *could* do func(lambda x: arr.__setitem__(x, y)). But you
probably shouldn't ;)

-Andrew.
Jul 18 '05 #7
fo******@iname.com (Follower) wrote in message news:<d2**************************@posting.google. com>...
Of course, now that I think about it, I could have also written:
self.assertEqual (foo.has_key ('bar')), 0)


ObMinimalism attempt:

self.failIf(foo.has_key('bar'))


That's not really minimalism (ObMinimalism=Obfuscation Minimalism?
That even less!). That is actually The way to do it. You can just
read it out loud and it makes sense immediately.
Jul 18 '05 #8
Hannu Kankaanpää wrote:

fo******@iname.com (Follower) wrote in message news:<d2**************************@posting.google. com>...
Of course, now that I think about it, I could have also written:
self.assertEqual (foo.has_key ('bar')), 0)


ObMinimalism attempt:

self.failIf(foo.has_key('bar'))


That's not really minimalism (ObMinimalism=Obfuscation Minimalism?
That even less!). That is actually The way to do it. You can just
read it out loud and it makes sense immediately.


Some folks prefer to stick with the positive logic (assert X)
always, rather than risk confusion by mixing and matching in an
arbitrary manner.

Personally, I couldn't keep the negative logic of the "fail X"
style straight and had to give it up.

-Peter
Jul 18 '05 #9
>(ObMinimalism=Obfuscation Minimalism?
Ob = Obligatory (Old school Usenet idiom...)

This was in reference to the seemingly eternal programmer desire to
reduce key strokes. And, as mentioned elsewhere, this is even fewer:

self.failIf("bar" in foo)
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

53
by: Oliver Fromme | last post by:
Hi, I'm trying to write a Python function that parses an expression and builds a function tree from it (recursively). During parsing, lambda functions for the the terms and sub-expressions...
63
by: Stephen Thorne | last post by:
Hi guys, I'm a little worried about the expected disappearance of lambda in python3000. I've had my brain badly broken by functional programming in the past, and I would hate to see things...
26
by: Steven Bethard | last post by:
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...
181
by: Tom Anderson | last post by:
Comrades, During our current discussion of the fate of functional constructs in python, someone brought up Guido's bull on the matter: http://www.artima.com/weblogs/viewpost.jsp?thread=98196 ...
3
by: Arnaud Diederen | last post by:
Hello, I've been looking in the archives but found no interesting answer to my problem. I was wondering why the following code does not work in IE 5; I'd expect an alert showing 'In finally!',...
25
by: Russell | last post by:
I want my code to be Python 3000 compliant, and hear that lambda is being eliminated. The problem is that I want to partially bind an existing function with a value "foo" that isn't known until...
4
by: Xah Lee | last post by:
A Lambda Logo Tour (and why LISP languages using λ as logo should not be looked upon kindly) Xah Lee, 2002-02 Dear lispers, The lambda character λ, always struck a awe in me, as with...
23
by: Kaz Kylheku | last post by:
I've been reading the recent cross-posted flamewar, and read Guido's article where he posits that embedding multi-line lambdas in expressions is an unsolvable puzzle. So for the last 15 minutes...
1
by: Tim H | last post by:
Compiling with g++ 4: This line: if_then_else_return(_1 == 0, 64, _1) When called with a bignum class as an argument yields: /usr/include/boost/lambda/if.hpp: In member function 'RET...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.