If the maximum depth of the tree cannot be accurately predicted, then you cannot use recursive way or you might encounter stack overflow unless you are able and willing to deal with system call stack.
You can, however, use a custom stack (list in python) record the data you need to process. And pop them out to examine, while append new task you found in that loop.
condition = lambda collect: "foobar" in collect.name
dosomething = lambda collect: None
dealing_stack = []
Blender store all collection in list not a tree (or a tree-liked list?)
for collect in bpy.data.collections:
if condition(collect) and collect not in dealing_stack:
dealing_stack.append(collect)
record processed object, not sure if id won't change in dealthis
processed_list = []
while dealing_stack:
dealthis = dealing_stack.pop()
try:
dosomething(dealthis)
except:
raise
finally:
processed_list.append(dealthis)
dealing_stack.extend(
[
obj
for obj in dealthis.children
if obj not in processed_list
]
)
While the recursive method indeed been more flexible in dealing with tree like structure:
condition = lambda collect: "foobar" in collect.name
dosomething = lambda collect: None
def deal_these_collection(collections, condition, callback=[]):
if not collections:
return
for subcollect in collections:
is_specified = condition(subcollect)
if isinstance(subcollect, list):
deal_these_collection(
collections = subcollect,
condition = lambda:True if is_specified else condition,
callback
)
elif is_specified:
for call in callback:
if callable(call):
call(subcollect)
else:
# not target
pass
deal_these_collection(bpy.data.collections, condition, [dosomething])
Please be aware of stack overflow problem when using recursion in large and deep tree, you must know your algorithm very well and prepare some stack memorization technique to prevent the problem and make your program more efficient.
Personal opinion
If a program can be written in iterative method, then use iterative unless using recursive will "Strongly" enhance the readability of code. When code is in Python, the readability should be consider first. Most of the recursive method will let other confuse what's going on in code, and also making it hard to debug.
So unless the problem you deal is commonly dealt in recursive way, and you can list up bunch of merit to use it. Just use iterative way. Writing iterative method in Python should be easy due to the python duck-type list and a lot of handy expression.
bpy.data.collectionsand set for the 50 of 100. – batFINGER Jul 21 '20 at 09:59