lambda (and reduce) are valuable

Steven Bethard steven.bethard at gmail.com
Mon Dec 12 02:46:28 EST 2005


Paul Rubin wrote:
> Chris Mellon <arkanes at gmail.com> 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)

STeVe



More information about the Python-list mailing list