lambda (and reduce) are valuable

bonono at bonono at
Mon Dec 12 09:39:08 CET 2005

Steven Bethard wrote:
> Paul Rubin wrote:
> > Chris Mellon <arkanes at> writes:
> >
> >>As someone who does a tremendous amount of event-driven GUI
> >>programming, I'd like to take a moment to speak out against people
> >>using us as a testament to the virtues of lamda. Event handlers are
> >>the most important part of event-driven code, and  making them real
> >>functions with real names is crucial to maintainable code. The only
> >>reason to ever use a lamdba in Python is because you don't want to
> >>give a function a name, and that is just not a compelling use case for
> >>GUI events.
> >
> >
> > I thought stuff like the following was idiomatic in GUI programming.
> > Do you really want separate names for all those callbacks?
> >
> > # generate calculator keypad buttons
> > Button(label='7', command=lambda: user_pressed(7)).grid(column=1, row=1)
> > Button(label='8', command=lambda: user_pressed(8)).grid(column=2, row=1)
> > Button(label='9', command=lambda: user_pressed(9)).grid(column=3, row=1)
> >
> > Button(label='4', command=lambda: user_pressed(4)).grid(column=1, row=2)
> > Button(label='5', command=lambda: user_pressed(5)).grid(column=2, row=2)
> > Button(label='6', command=lambda: user_pressed(6)).grid(column=3, row=2)
> > ...
> While I don't spend much time on GUIs, code like that would scream
> "refactor" to me, e.g. something like:
> class UserPressedButton(Button):
>      def __init__(self, i):
>          def command():
>              return user_pressed(i)
>          Button.__init__(self, label=str(i), command=command)
> Button(7).grid(column=1, row=1)
> Button(8).grid(column=2, row=1)
> Button(9).grid(column=3, row=1)
> Button(4).grid(column=1, row=2)
> Button(5).grid(column=2, row=2)
> Button(6).grid(column=3, row=2)
Well, that depends. This kind of coding many times are result of quick
copy and paste. Whether it worths to abstract things out really depends
on the life span. If it ends up never got touch again, the advntage of
lambda is that I can just have it as is, it works, is clear to
understand and everything is in place. I thought that is one of the
advantage of python or quick prototyping.

This also is not a very good example as it shows some form of
repetitiveness that is "screaming for refactoring". Many times, these
fields are similar but have no common functionalities.

More information about the Python-list mailing list