When programming in Maya, it is sometimes necessary to operate first on the leaf nodes in a DAG path, and then work your way back. One way to help with this is to query your scene (in this case, we’re looking for all transforms), sort your list by DAG path depth, then start iterating through every object.
This is a quick example of how to do such an operations using Python’s built-in sort function:
import maya.cmds as cmds
def getDAGPathLength(x):
"""Returns the length of the given DAG path"""
return len(x.split('|'))
# Query the transforms. Note the usage of the
# long-path flag. This is important.
objects = cmds.ls(l=True, type='transform')
# Print the results:
print '\nOriginal List:'
for obj in objects:
print obj
# The ls command returns a list of objects. Built
# into each list type in Python, there is a sort
# method. Note that the sort method operates
# in-place, so there is no return value. In other
# words, the original list is sorted.
objects.sort(key=getDAGPathLength, reverse=True)
# Print the new list:
print '\nSorted List'
for obj in objects:
print obj
In the above example, we use the sort function on the ‘objects’ list to sort in place. The ‘key’ argument of the sort method allows us to specify a function to run on each item before the comparison operation takes place. In this case, we will call the ‘getDAGPathLength’ function.
The length of a DAG path can easily be determined by simply counting the number of pipe characters in the object. By sending the length of the DAG path, instead of the DAG path itself, we can sort by the depth. In this example, the ‘reverse’ keyword is used to have the deepest DAG paths sort at the top of the list instead of the bottom.
If we really wanted to be cool, instead of using the ‘getDAGPathLength’ function, we can write our sort method in one line, using the ‘lambda’ functionality in Python:
# Use a lambda function to rewrite the DAG sort in a single line,
# instead of using the getDAGPathLength function.
objects.sort(key=lambda x: len(x.split('|')), reverse=True)
Now we can do some interesting things to this list, such as renaming objects to remove namespaces!
Finally, note that this general concept can also be used to sort file-trees, XML document elements, or anything else that can be represented by hierarchical information.