I'm doing a little game in Python 3.2 with use of PyQt. I needed to insert in menu actions which did almost the same, but with other parameters. I figured out I will do it with use of lambdas, but it turned out that all actions got the same parameter.
It turned out to be a closure problem, which i solved according to this post on other SO question. But one of the proposed solutions (with default argument) which should be equivalent to the other one, doesn't work. When I did a little test with print function both solutions were equal.
I'd like to understand it why it works different in this case. Is connect method influencing it somehow? It probably has something to do with python scopes. Here a snippet of what I'm doing (I omitted assigning names and text to actions):
cardsOptions = [15, 30, 45, 50, 55, 60, 10]
self.startActions = []
lambdas = []
for co in cardsOptions:
action = QtGui.QAction(MainWindow)
self.menuNewGame.addAction(action)
# This works
# action.triggered.connect(partial(self.StartGame, 8, co))
lamb = (lambda a = co: self.StartGame(8, a))
lambdas.append(lamb)
# This doesn't work, when StartGame is called it gets arguments 8, false
action.triggered.connect(lamb)
self.startActions.append(action)
# This proves that closure was done ok, and it saved all co values
[m() for m in lambdas]
What surprise me the most is that it passes false as second argument, as if he evaluated a = co? So how closure with default argument is different from using partial, that it works this way?