title: Will a Python generator be garbage collected if it will not be used any more but hasn't reached StopIteration yet?
body: <p>When a generator is not used any more, it should be garbage collected, right? I tried the following code but I am not sure which part I was wrong.</p>
  
  <pre><code>import weakref
  import gc
  
  def countdown(n):
      while n:
          yield n
          n-=1
  
  cd = countdown(10)
  cdw = weakref.ref(cd)()
  print cd.next()
  gc.collect()
  print cd.next()
  gc.collect()
  print cdw.next()
  </code></pre>
  
  <p>On the second last line, I called garbage collector and since there is no call to <code>cd</code> any more. <code>gc</code> should free <code>cd</code> right. But when I call <code>cdw.next()</code>, it is still printing 8. I tried a few more <code>cdw.next()</code>, it could successfully print all the rest until StopIteration.</p>
  
  <p>I tried this because I wanted to understand how generator and coroutine work. On slide 28 of David Beazley's PyCon presentation "A Curious Course on Coroutines and Concurrency", he said that a coroutine might run indefinitely and we should use <code>.close()</code> to shut it down. Then he said that garbage collector will call <code>.close()</code>. In my understanding, once we called <code>.close()</code> ourselves, <code>gc</code> will call <code>.close()</code> again. Will <code>gc</code> receive a warning that it can't call <code>.close()</code> on an already closed coroutine?</p>
  
  <p>Thanks for any inputs.</p>