title: Can I memoize a Python generator?
body: <p>I have a function called <code>runquery</code> that makes calls to a database and then yields the rows, one by one. I wrote a memoize decorator (or more accurately, I just stole one from <a href="https://stackoverflow.com/questions/3377258/memoization-handler/3377272#3377272">this stackoverflow question</a>) but on subsequent calls it just yields an empty sequence, presumably because a generator's values can only be yielded once.</p>
  
  <p>How could I modify the memoization decorator that works for Python generators? I realise I will need to store it in memory at some point but I'd like to handle this within the decorator and not modify the original function.</p>
  
  <p>The current code of the memoization function is:</p>
  
  <pre><code>def memoized(f):
      # Warning: Doesn't work if f yields values
      cache={}
      def ret(*args):
          if args in cache:
              return cache[args]
          else:
              answer=f(*args)
              cache[args]=answer
              return answer
      return ret
  </code></pre>