Monthly Archives: February 2009

Stupid Lambda

The first time I read about Lambda functions in Python I thought to myself, “Gee, that’s stupid! An anonymous function that can only return one expression. I’m never gonna use it.”

Well I’m here to tell you that because its so stupid, it manages to solves a tricky problem in PyQt Signals and Slots. Here’s a typical signal/slot to run a function self.F based on when a QPushButton self.B is clicked:

self.connect(self.B, SIGNAL(“clicked()”), self.F)

Not too complicated. But now I want to pass a couple local variables (v0 and v1) to that function when the button is clicked. I don’t want to have to use global variables but instead want to use the signal/slot to pass the information directly.

self.connect(self.B, SIGNAL(“clicked()”), self.F(v0, v1))

Nice try, but it won’t work. You can’t pass variables that way. Enter the “Stupid” Lambda function.

self.connect(self.B, SIGNAL(“clicked()”), lambda Stupid=[v0, v1]: self.F(Stupid))

By packing the variables (as many as you like) into a list and then building a Lambda function “Stupid” that returns the list, the above signal/slot works because the variables are not being passed directly, only the Lambda function name. So if the function self.F looks like this:

def F (self, v):

then the values of v0 and v1 are now accessable via v[0] and v[1] within that function. Cool eh? And by using a list, you can pass as many stupid things as you like.