1
$\begingroup$

I am making a function that will get the top-most parent using recursion. I must be missing some logic because it seems like it should work to me. I even print the obj.name right before returning it, but it ends up returning "None".

import bpy


def main():

    def get_parent_object(obj):
        parent = obj.parent
        
        if parent != None:
            get_parent_object(parent)

        else:
            print(obj.name)
            return obj
    
    selected_objects = bpy.context.selected_objects
    
    for obj in selected_objects:
        print(get_parent_object(obj))


if __name__ == "__main__":
    main()

Any help is much appreciated! Thanks

$\endgroup$
1
  • $\begingroup$ Hello! you need to return get_parent_object(parent). As it stands, your function scope ends without any return statement in case parent != None which implicitely returns None in python. $\endgroup$
    – Gorgious
    Jan 19, 2023 at 16:06

1 Answer 1

2
$\begingroup$

I'll suggest another method that will not throw a RecursionError in case you have a really complicated setup with hundreds of parents.

import bpy

obj = bpy.context.active_object
ancestor = obj
while ancestor.parent is not None:
    ancestor = ancestor.parent
print(ancestor)
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .