lambda question

Greg Ewing (using news.cis.dfn.de) me at privacy.net
Thu Mar 13 02:12:35 CET 2003


David Bear wrote:
> Still I am 
> wondering if this is a valid use of the lambda function.  Anyone have 
> comments on where lambda's are most usefull?

There's nothing wrong with it, but it's rather
unusual style-wise, and it's no more (or less)
efficient than using a def.

Lambdas are most useful when you can embed them
in another expression. Typical uses include creating
callbacks for plugging into GUI widgets, e.g.

   import Tkinter, sys
   win = Tkinter.Tk()

   def make_button_which_prints(s):
     b = Tkinter.Button(win,
       text = s,
       command = lambda: sys.stdout.write(s + "\n"))
     b.pack()

   make_button_which_prints("Hello")
   make_button_which_prints("Goodbye")
   make_button_which_prints("Ftang!")

   win.mainloop()

-- 
Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand
http://www.cosc.canterbury.ac.nz/~greg





More information about the Python-list mailing list