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

Chris Barker chrishbarker at home.net
Tue Jun 26 15:03:44 EDT 2001


Joe Potter wrote:
> >>     # 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)

> My question is *why* the lambda is allowed to call the perfectly defined function
> fetch, but a direct call of fetch is not.

Rainer tried, but I'll use more words and see if that makes it clearer.

> In the 6 or 7 other languages I have used over time --- if you call a defined
> function it works --- but in Python there is a mystery here.

yes, if you call a defined function it works, the question is when is
the function called?

In your version, the "fetch" function is called when this code is run,
so command gets set to the result of calling fetch(vars), using the
value of vars at that time. fetch returns nothing, so you get comamnd
set to None. What you want is for command to be set to a function, not
the result of the function.

What lambda does is create a function without giving it a name. You
could also have done:

     def command_fun(v = vars):
         return fetch(v)
     Button(root, text='Fetch',command=command_fun).pack(side=LEFT)

> Or, perhaps the mystery is deep down in Tkinter?

Sort of. When the button is pressed, the function that command is set to
is called. So why can't you do?:

     Button(root, text='Fetch',command=fetch).pack(side=LEFT)

Because when the button is pressed, no parameters will be passed to the
command function, and fetch needs a list of variable to be passed in.
That's what the default parameter assignment does: my command_fun (or
the lambda function) does not need to have any parameters passed to it,
it will assign v to vars, and then pass that in to fetch.

I'm not sure I made this very clear, but I tried 

-Chris


-- 
Christopher Barker,
Ph.D.                                                           
ChrisHBarker at home.net                 ---           ---           ---
http://members.home.net/barkerlohmann ---@@       -----@@       -----@@
                                   ------@@@     ------@@@     ------@@@
Oil Spill Modeling                ------   @    ------   @   ------   @
Water Resources Engineering       -------      ---------     --------    
Coastal and Fluvial Hydrodynamics --------------------------------------
------------------------------------------------------------------------



More information about the Python-list mailing list