title: Stop generator from within block in Python
body: <p>I have a generator that yields nodes from a Directed Acyclic Graph (DAG), depth first:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>I can iterate over the nodes like this</p>
  
  <pre><code>for node, depth in graph.depth_first_search():
      # do something
  </code></pre>
  
  <p>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. </p>
  
  <p>I came up with the following solution, that use an external function.</p>
  
  <pre><code>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
  </code></pre>
  
  <p>This solution forces me to declare variables I need before stop_crit is defined so they can be accessed from it.</p>
  
  <p>In Ruby, yield returns the last expression from the block so this could conveniently be used to tell the generator to continue or stop.</p>
  
  <p>What is the best way to achieve this functionality in Python?</p>