I really don't understand Lambda!

Hans Nowak wurmy at earthlink.net
Thu Oct 10 20:50:04 EDT 2002


Bob van der Poel wrote:

> Just when I thought I was understanding lambda, it totally confuses me.
> I have the following statement in my program, which works:
> 
> 	wg.bind("<Return>", lambda s=wg: seq.setSize(wg) )
> 
> In this case 'wg' is a tkinter Entry widget and seq.setSize is a class
> method which extracts some data from the widget, etc. So far, so good.
> 
> However, originally, I had tried:
> 
> 	wg.bind("<Return>", lambda s=wg: seq.setSize(s) )
> 
> And this doesn't work. Instead of passing a reference to the Entry, it
> passes the event. Clearly not what I wanted.
> 
> So, if we don't need to use the variable, why not leave out the
> assignment:
> 
> 	wg.bind("<Return>", lambda : seq.setSize(wg) )
> 
> Nope, seems we have to have some kind of arg, dummy or otherwise.

This has nothing to do with lambda per se. It's just that you're binding an 
event handler to a widget, and the handler is expected to have at least (?) one 
argument, which will contain the event data. Like this:

def callback(event):
     print "clicked at", event.x, event.y

More information here:

http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm

In your case,

   wg.bind("<Return>", lambda s=wg: seq.setSize(wg) )

you used an argument for the event, but you called it s and bound it to wg. It 
isn't correct, but apparently this did not have side effects for you, since you 
report that it worked.

This:

   wg.bind("<Return>", lambda s=wg: seq.setSize(s) )

doesn't work, since you pass the event (here called 's') to seq.setSize. (The 
default value 'wg' doesn't matter because the function is later called with the 
event object, thus overriding the default.) And this:

   wg.bind("<Return>", lambda : seq.setSize(wg) )

doesn't have an argument for the event, so it won't work.

> So, (1) do we always need some kind of assignment between the 'lambda'
> and the ':'?

No. It's not assignment by the way, it's setting the values of default 
arguments, much like in "regular" functions:

   def p(a, b="hello"):
       ...

HTH,

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.awaretek.com/nowak/kaa.html




More information about the Python-list mailing list