I have a generator that yields nodes from a Directed Acyclic Graph (DAG), depth first:
def depth_first_search(self):
yield self, 0 # root
for child in self.get_child_nodes():
for node, depth in child.depth_first_search():
yield node, depth+1
I can iterate over the nodes like this
for node, depth in graph.depth_first_search():
# do something
I would like to be able to tell the generator, from the for loop, to stop from going deeper in the graph if some condition is met.
I came up with the following solution, that use an external function.
def depth_first_search(self, stop_crit=lambda n,d: False):
yield self, 0 # root
for child in self.get_child_nodes():
for node, depth in child.depth_first_search():
yield node, depth+1
if stop_crit(node, depth): break
This solution forces me to declare variables I need before stop_crit is defined so they can be accessed from it.
In Ruby, yield returns the last expression from the block so this could conveniently be used to tell the generator to continue or stop.
What is the best way to achieve this functionality in Python?