title: Best way to receive the 'return' value from a python generator
body: <p>Since Python 3.3, if a generator function returns a value, that becomes the value for the StopIteration exception that is raised. This can be collected a number of ways:</p>
  <ul>
  <li>The value of a <code>yield from</code> expression, which implies the enclosing function is also a generator.</li>
  <li>Wrapping a call to <code>next()</code> or <code>.send()</code> in a try/except block.</li>
  </ul>
  <p>However, if I'm simply wanting to iterate over the generator in a for loop - the easiest way - there doesn't appear to be a way to collect the value of the StopIteration exception, and thus the return value. Im using a simple example where the generator yields values, and returns some kind of summary at the end (running totals, averages, timing statistics, etc).</p>
  <pre><code>for i in produce_values():
      do_something(i)
  
  values_summary = ....??
  </code></pre>
  <p>One way is to handle the loop myself:</p>
  <pre><code>values_iter = produce_values()
  try:
      while True:
          i = next(values_iter)
          do_something(i)
  except StopIteration as e:
      values_summary = e.value
  </code></pre>
  <p>But this throws away the simplicity of the for loop. I can't use <code>yield from</code> since that requires the calling code to be, itself, a generator. Is there a simpler way than the roll-ones-own for loop shown above?</p>