Hey there. So this is caused by the fact that a python lambda does not perform a full closure over the scoped variable, which leads to bugs like this when the locally scope variable (n) is changing over the course of the loop. Each lambda you are passing as a slot function has a reference to that scope, but will evaluate the last value of the variable n.
(note: dont do the following)
The safer way to express the lambda that properly captures the variable value at that time is something like this double-lambda:
fn = lambda val: lambda: self.fooPrint(n)
btn.clicked.connect(fn(n))
This directly captures the current value of your loop variable and returns a new lambda with a closure over that value.
So what you could do instead is wrap local def functions (there are multiple ways to do this, but here is one way):
for n in 'ABCD':
def wrap(val=n, *args):
self.fooPrint(val)
btn.clicked.connect(wrap)
And this is pretty much what functools.partial() is for:
from functools import partial
for n in 'ABCD':
btn.clicked.connect(partial(self.fooPrint, n))
thanks
R
--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/eeb1960d-1e46-43d0-a0d9-1107f695a859n%40googlegroups.com.