[wxPython-users] Re: using lambda to pass args to event function

Robin Dunn robin at alldunn.com
Tue Jan 2 08:59:13 PST 2007


Christian Kristukat wrote:
> Hi Christopher,
> 
> Christopher Barker <Chris.Barker <at> noaa.gov> writes:
>> Ben North wrote:
>>>> def makeArgsHandler(handler, arg):
>>>>      return lambda event: handler(event, arg)
>>>    from functional import rcurry
>>>    self.Bind(wx.EVT_BUTTON,
>>>              rcurry(controller.PopulateMainList, 'pkl'),
>>>              id = ID_PKL_BUTTON)
>> pretty cool.
>>
>> however, for an example this simple, you may be able to make use us 
>> default arguments:
>>
>>      self.Bind(wx.EVT_BUTTON,
>>                lambda event: handler(event, arg=current_arg),
>>                id = ID_PKL_BUTTON)
>>
>> now arg will get set to whatever current_arg is when that Bind call is 
>> executed -- i.e. in the Window __init__, usually.
> 
> I found this old posting where you presented a way to pass arguments 
> along with the event object to an event handler.
> That does not work, at least with python 2.4 on linux. When you put the call
> to Bind in a loop the event handler always receives the last value of 
> current_arg of the loop. Are you sure this should work?

It works if you make it an arg of the lambda with a default value, like 
this:

       self.Bind(wx.EVT_BUTTON,
                 lambda event, ca=current_arg: handler(event, arg=ca),
                 id = ID_PKL_BUTTON)

This way the reference to current_arg is evaluated and bound at the time 
that the lambda is created, rather than the time it is executed.

-- 
Robin Dunn
Software Craftsman
http://wxPython.org  Java give you jitters?  Relax with wxPython!





More information about the wxpython-users mailing list