-1

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.

Elias Finoli
  • 121
  • 9

4 Answers4

2

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.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
1

Your getAllParents method takes a string and returns a list. Then you insert this list into another list which makes it a list of strings and lists of strings and lists...

To concatenate two lists you can simply use + operator, so:

prnts = getAllParents(prnt) + parents
Kevin Fang
  • 1,966
  • 2
  • 16
  • 31
0

Keep in mind that you're using list functions like append, insert passing list. In this case you'll end-up to weird results. For instance

a = [1, 2, 3]
b = [4, 5]
print(a.append(b))

>> [1, 2, 3, [4, 5]]
Massimo Costa
  • 1,864
  • 15
  • 23
0

I don't know python but I guess the following code works fine

listPrts = ["","toto","idiot","happy"]

def getParent(jnt):
    something = listPrts
    del listPrts[0]
    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 parents


selection = "childof"

parents = getAllParents(selection)

print '\n'
print parents
lue
  • 25
  • 6