title: Understanding nested yield / return in python
body: <p>I have a function in python whose output is a generator  :</p>
  
  <pre><code>def main_function(x):
      r = get_range()
      for i in range(r):
          yield x+i
  </code></pre>
  
  <p>I want to refactor the code (I've simplified the use case but actual computation might be complex &amp; longer. Please see EDIT below). Based on my understanding, this is what I should do to keep the functionality unchanged :</p>
  
  <p>(a) Same interface as original code</p>
  
  <pre><code>    def sub_function(x,r):
          for i in range(r):
              yield x+i    
  
      def main_function(x):
          r = get_range()
          return sub_function(x,r)
  </code></pre>
  
  <p><strong>As compared to other approaches where :</strong>  </p>
  
  <p>(b) This would return a generator of a generator (Are there any advantages of this approach ?)</p>
  
  <pre><code>    def sub_function(x,r):
          for i in range(r):
              yield x+i    
  
      def main_function(x):
          r = get_range()
          yield sub_function(x,r)
  </code></pre>
  
  <p>(c) This would defeat the purpose of a generator (Is that correct?)</p>
  
  <pre><code>    def sub_function(x,r):
          return [x+i for i in range(r)]
  
      def main_function(x):
          r = get_range()
          for i in sub_function(x,r):
              yield(i)
  </code></pre>
  
  <p><strong>EDIT</strong> : Comments point out that the right answer is use case dependent. I want to add that my use case is parsing an XML file to extract fields and write them to a database. This part is delegated to sub_function(). I also asked this question for a general understanding of the usage of nested yield for refactoring code. </p>