maya Creating Maya UI Lambdas and loops


Example

Lambdas are a useful shortcut for hooking up behaviors to GUI elements.

b = cmds.button("make a cube", command = lambda _: cmds.polyCube())

However, due to the way Python captures variables inside of lambdas, you can get unexpected results if you bind commands using lambdas inside a loop. For example this looks like it should produce buttons that create spheres of different sizes:

# warning: doesn't work like it looks!
for n in range(5):
    b = cmds.button("sphere size %i" % n, command = lambda _: cmds.polySphere(radius=n))

The buttons will be labelled correctly but will all use the same radius (4) because the lambdas will all capture that value when the loop closes. TLDR: If you're generating callbacks inside of a loop, use functools.partial or another method for capturing values - lambdas don't work for this application. See here for more details