newbie with major "lambda" problem (perhaps a scope problem as well)

Garry Hodgson garry at sage.att.com
Tue Jun 26 13:18:31 EDT 2001


Joe Potter wrote:
> 
> On Tue, 26 Jun 2001 16:09:06 GMT, "Rainer Deyke" <root at rainerdeyke.com> wrote:
> 
> >"Joe Potter" <jm7potter at hotmail.com> wrote in message
> >news:j5ahjtkfmf32lkqtap0q1u6rig385d7b5i at 4ax.com...
> >>     # the "button" below works like a champ !!
> >>     #Button(root, text='Fetch',
> >>                  #command=(lambda v=vars: fetch(v))).pack(side=LEFT)
> >>
> >>     # the "button" below does not do anything ??????
> >>     Button(root, text='Fetch', command=(fetch(vars))).pack(side=LEFT)
> >
> >Of course this doesn't work.  It calls 'fetch(vars)', and passes the result
> >to 'Button'.  Use the lambda, that's what it's there for.  Or use one of the
> >'curry' alternatives (see archives).
> 
> My question is *why* the lambda is allowed to call the perfectly defined function
> fetch, but a direct call of fetch is not.
> 
> In other words --- I already knew that I had to use lambda, but I do not know why!

lambda is a special kind of function.  it creates, on the fly, another,
un-named
function, and returns that as its value (much like def, but def also
binds the
function to a name).  so the first (commented out) case above
sets command equal to a function, which will be called when the button
is clicked.
in the latter (non-working) case, you actually run your fetch function
when this code
is executed, and then bind whatever it returned to the command
variable.  when you later
click your button, tkinter tries to use this value as a callback
funtion, and will fail.
i'm surprised you don't get an exception.

---
Garry Hodgson                   sometimes we ride on your horses
Senior Hacker                   sometimes we walk alone
Software Innovation Services    sometimes the songs that we hear
AT&T Labs                       are just songs of our own
garry at sage.att.com



More information about the Python-list mailing list