.listRelatives() – List an objects relatives in Maya using Python
We can use this method to find the relatives of an object, this follows on from the .objectType() documentation. Lets take a look as some example code:
If you intend to run this code, be sure to add a few objects to your maya scene, for this example we have added 3 different mesh objects (cone, 2x cube, cylinder).
from maya import cmds selection = cmds.ls(selection=True) if len(selection) == 0: selection = cmds.ls(dag=True, long=True) selection.sort(key=len, reverse=True) for obj in selection: shortName = obj.split("|")[-1] # Lets create a new variable to store the relatives: # We want to list the relatives, we only want the children, and we want the full path children = cmds.listRelatives(obj, children=True, fullPath=True) # Lets print the new variable on each iteration through the loop print children
After running this code we get the following output:
[u'|pCylinder1|pCylinderShape1'] [u'|pCube1|pCubeShape1'] [u'|pCone1|pConeShape1'] [u'|pCube2|pCubeShape2']
Great, we can see the object types including the path.
Adding a cheeky fall-back
One of the first things that the example code does is check if an object is selected:
selection = cmds.ls(selection=True)
And if it is not, then gets all of the objects:
if len(selection) == 0: selection = cmds.ls(dag=True, long=True)
Then a little later on, we try to find all of the children of the selected object, or all of the objects (if none selected):
children = cmds.listRelatives(obj, children=True, fullPath=True)
But what if our selected object has no relatives? To see what happens select the ‘defaultLightSet’ in the outliner.
Then run our code, the output will be ‘None’
The output is correct, but it isn’t very useful! None? We can do better than that! We can add an ‘or’ condition to the .listRelatives() method in the ‘children’ variable:
children = cmds.listRelatives(obj, children=True, fullPath=True) or 
If we run our code again, we get an empty list instead of ‘None’, so no matter what happens we always know that ‘children’ will always be of a consistent object type (in this case: list).