python generators garbage collection : <p>I think my question is related to <a href="https://stackoverflow.com/questions/15490127/will-a-python-generator-be-garbage-collected-if-it-will-not-be-used-any-more-but">this</a>, but not exactly similar. Consider this code:</p>

<pre><code>def countdown(n):
    try:
        while n &gt; 0:
            yield n
            n -= 1
    finally:
        print('In the finally block')

def main():
    for n in countdown(10):
        if n == 5:
            break
        print('Counting... ', n)
    print('Finished counting')

main()
</code></pre>

<p>The output of this code is:</p>

<pre><code>Counting...  10      
Counting...  9       
Counting...  8       
Counting...  7       
Counting...  6       
In the finally block 
Finished counting  
</code></pre>

<p>Is it guaranteed that the line "In the finally block" is going to be printed before "Finished counting"? Or is this because of cPython implementation detail that an object will be garbage collected when the reference count reaches 0.</p>

<p>Also I am curious on how <code>finally</code> block of the <code>countdown</code> generator is executed? e.g. if I change the code of <code>main</code> to</p>

<pre><code>def main():
    c = countdown(10)
    for n in c:
        if n == 5:
            break
        print('Counting... ', n)
    print('Finished counting')
</code></pre>

<p>then I do see <code>Finished counting</code> printed before <code>In the finally block</code>. How does the garbage collector directly go to the <code>finally</code> block? I think I have always taken <code>try/except/finally</code> on its face value, but thinking in the context of generators is making me think twice about it. </p>
