Maya find all parents

So I was trying to find the best way to get the names of every parent of an object (so if you had a object parented under a group the group could be further nested under others).

Off the top of my head, two ideas I have would be:

  1. use listRelative to find the parent, and then recursion to continue up the chain of parents saving each to a list
  2. get the ‘fullPath’ or ‘long’ name of the current object with say the ls command and parse the string for the names

What do you think is the best method or do you have another even better method?

thanks

I would just split the full path to the node.

parents = cmds.ls(node, long=True)[0].split('|')[1:-1]
# This is depending on the order you want the parents in
parents.reverse()

Or if you’re using pymel, node.getAllParents()

The only time I’d use listRelatives recursively is if you wanted to account for instancing and trace multiple parent paths. But even then maybe this would list the full path to all parents
cmds.listRelatives(node, allParents=True, fullPath=True) [?].

Path splits for parentage, but recursive calls to listrelatives if you want to visit the nodes along the way up.

thanks, that’s what I was thinking was probably the best. I try to avoid the recursion unless necessary.

parents = cmds.ls(node, long=True)[0].split(’|’)[1:-1]

should work nicely. thanks again

After looking at it again if I need the full path of each of the parents then I would have to use recursion correct? Because if you do

parents = cmds.ls(node, long=True)[0].split(’|’)[1:-1]

It gets you the name but you can’t then do a listRelatives on those names because the name may not be unique.

If you’ve not messed with the list of parents yet, you can turn it back into long names pretty easily. You just do a join on the parents instead of splitting.
Which would let you avoid having to do recursive listRelative calls.

parents = cmds.ls(node, long=True)[0].split(’|’)[1:-1]
parents_long_named = [’|’.join(parents[:i]) for i in xrange(1, 1 + len(parents))]

Code golf clap!

[QUOTE=R.White;25498]If you’ve not messed with the list of parents yet, you can turn it back into long names pretty easily. You just do a join on the parents instead of splitting.
Which would let you avoid having to do recursive listRelative calls.

parents = cmds.ls(node, long=True)[0].split(’|’)[1:-1]
parents_long_named = [’|’.join(parents[:i]) for i in xrange(1, 1 + len(parents))][/QUOTE]

Very cool, thanks. When I have a chance maybe I’ll try it that way. I had already gone ahead and made a recursive function. Seems to be working pretty well, thus far.