I have a database that models a foldering relationship to n
levels of nesting. For any given folder, I want to generate a list of all child folders.
Assuming I have a function called getChildFolders()
, what is the most efficient way to call this kind of recursive loop?
The following code works for 4 levels of nesting, but I'd like more flexibility in either specifying the depth of recursion, or in intelligently stopping the loop when there are no more children to follow.
folder_ids = []
folder_ids.append(folder.id)
for entry in child_folders:
folder_ids.append(entry.id)
child_folders_1 = getChildFolders(entry.id)
for entry_1 in child_folders_1:
folder_ids.append(entry_1.id)
child_folders_2 = getChildFolders(entry_1.id)
for entry_2 in child_folders_2:
folder_ids.append(entry_2.id)
child_folders_3 = getChildFolders(entry_2.id)
for entry_3 in child_folders_3:
folder_ids.append(entry_3.id)
A recursive function is a nice way to do this:
This is the closest to your code, and very unpythonic:
You should probably look for
os.walk
and take a similar approach to walk the tree iteratively.I generally avoid recursion like the plague in python because it's slow and because of the whole stack overflow error thing.
This assumes that
getChildFolders
returns an empty list when there are no children. If it does something else, like return a sentinel value or raise an exception, then modifications will have to be made.I needed something similar once to check a hierarchic tree. You could try: