Lambda function and variable region

Currently my code is as follows:

for control in self.controls(): self.connect(control, SIGNAL('clicked()'), lambda: self.button(control.objectName())) 

When I run my code, my lambda function takes control as the last element in my list of elements, which I do not expect.

Oddly enough, when I manually run the lambda loop in each loop, it works fine for each loop, but still has the same problem as before, at the end:

 for control in self.controls(): func = lambda: self.button(control.objectName()) func() # Prints the correct output self.connect(control, SIGNAL('clicked()'), func) # When triggered, still breaks 

My self.button() function is defined trivially:

 def button(self, name): print name 

I checked the uniqueness of the control and func each loop by printing the output of id(control) and id(func) and they all returned unique numbers. In addition, control.objectName() is the correct object name.

I have the feeling that this is a variable scope problem since I usually don't use lambda often in my code. Does anyone see blatant errors?

+4
source share
1 answer

Splat.

 for control in self.controls(): self.connect(control, SIGNAL('clicked()'), lambda control=control: self.button(control.objectName())) 
+2
source

Source: https://habr.com/ru/post/1412702/


All Articles