lambda and map in Maya
Starting using a couple shorthand techniques today via map and lambda to save on screen real estate when authoring Python modules in Maya. I often times will troll the scene for info and want to print stuff:
Here, I find the transform name for all mesh in the scene, then print them all with tabs in front:
import sys import maya.cmds as mc # Get transform for each mesh: shapes = mc.ls(type='mesh') transforms = map(lambda x: mc.listRelatives(x, parent=True)[0], shapes) # print with tab in front: map(lambda x: sys.stdout.write('\t%s\n'%x), transforms)
By using our map / lambda combo, I’m able to side-step the need to write any loops. Here’s how it would look otherwise:
import maya.cmds as mc # Get transform for each mesh: shapes = mc.ls(type='mesh') transforms = [] for s in shapes: transforms.append(mc.listRelatives(s, parent=True)[0]) # print with tab in front: for tran in transforms: print '\t', tran
Not counting imports and comments, I halved the number of lines of code. One could argue the bottom example is possibly more readable however.