Search code examples
pythonpymel

list returned from recursive function always empty


Im trying to return a list from a recursive function, appending to this list for each depth, but the final returned list is always empty. I'm not very experienced pythonian so it might be a trivial mistake.

Here's the code:

import pymel.core as pm

def getParent(jnt):
    something = pm.listRelatives(jnt, parent=True);
    if something:
        print 'got parent: ' + something[0]
        return something[0]
    else:
        return None

def getAllParents(jnt):
    parents = []
    parents.append(jnt)
    prnt = getParent(jnt)
    if prnt == None:
        return parents
    else:
        prnts = parents.insert(0, getAllParents(prnt))
        return prnts


selection = pm.ls(sl=True)[0]

parents = getAllParents(selection)

print '\n'
print parents

pm.listRelatives(jnt, parent=True); returns a list of strings, of which i grab the first if it is not empty.

Here's the output:

got parent: joint3
got parent: joint2
got parent: joint1


None

Any help appreciated.


Solution

  • Here:

    def getAllParents(jnt):
        # ...
        prnts = parents.insert(0, getAllParents(prnt))
        return prnts
    

    list.insert() (as well as all methods that modify a list in place - sort() etc) returns None. You want:

        parents.insert(0, getAllParents(prnt))
        return parents
    

    instead.