So I've been writing this application that works with files , and I wanted to add a list of recently opened files in the "File" menu and I came across a weird bug ..

Here's the sample code ..

for path in recentFilesList:
    item = wx.MenuItem(menu, wx.NewId(), path)
    self.Bind(wx.EVT_MENU, lambda(event):self.LoadRecent(path), item)

so the problem is that the last lambda function gets bound to ALL the items added this way ..

so for instance , if

recentFileList[-1] = "C:\Last\File\Path"

clicking on any of those items


gets called ..

Am I missing something , or is this just a bug ?

7 Years
Discussion Span
Last Post by loading...

it is not a bug. Your trouble is that in the scope of of your lambda function, path is a global variable, and by the end of the loop and forever more
path == recentFileList[-1]
Thus everytime one of your lambda functions is called it uses that value in loadRecent(...)

To come about it, you need to assign the value of path to a local variable (ie. local to your lambda function), and use that variable to call loadRecent:

lambda event,p=path: self.loadRecent(p)

you may name the local variable "path" also if you desire, but I have named it "p" for clarity, thus

lambda event,path=path: self.loadRecent(path)

is quite valid too.


This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.