Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automizing deeply nested function python

Tags:

python

I have a database model with deeply nested children. I am trying to add add all of the underlying ids (of all levels) to a dictionary entry. My current code looks as follows:

children = obj.children
    for child in children:
        data["children_ids"].append(child.id)
        for child in child.children:
            data["children_ids"].append(child.id)
            for child in child.children:
                data["children_ids"].append(child.id)
                for child in child.children:
                    data["children_ids"].append(child.id)

This code is fully functional, but the problem is fairly obvious. I don't want to keep writing the same code over and over again: it's ugly, impractical and not very maintainable. How would I do this?

like image 827
Ben Avatar asked Apr 02 '26 06:04

Ben


1 Answers

Use a recursive function to run the same code on different children:

def add_children_ids(ids, children):
    for child in children:
        ids.append(child.id)
        add_children_ids(ids, child.children)

children = obj.children
data['children_ids'] = []
add_children_ids(data['children_ids'], children)

Because ids is a mutable list, there's no need to return it

like image 65
mhlester Avatar answered Apr 03 '26 21:04

mhlester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!