You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Python生成器break后finally块执行确定性的技术问询

Will the "In the finally block" line always print in this Python generator code?

Problem Description

Here's the code in question:

def countdown(n):
    try:
        while n > 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()

The output includes In the finally block, but I'm wondering: can we guarantee this line will always print?


Answer

Great question! Let's break this down clearly:

In the exact code you provided, you can almost always rely on that finally block running—here's the reasoning:
When you break out of the for loop, the generator iterator returned by countdown(10) loses all references to it. In CPython (the standard Python implementation), this immediately drops the reference count to 0, triggering garbage collection for the generator. During cleanup, Python calls the generator's close() method, which raises a GeneratorExit inside the generator. This exception triggers the finally clause attached to the try block, so your print statement runs as expected.

That said, there are a few edge cases where the finally block won't execute:

  • If the generator is still referenced elsewhere: Suppose you assigned gen = countdown(10) and reused that variable later—if gen is a global variable or held by another active object, it won't be garbage collected, so close() never gets called.
  • Immediate program termination: If the program exits abruptly before garbage collection runs (e.g., calling os._exit(), or getting killed by a system signal like SIGKILL), the generator never gets cleaned up, so the finally block won't run.
  • Non-standard Python implementations: Some alternative runtimes (like PyPy) have different garbage collection timelines, but even then, once the generator is marked for collection, the finally block will execute.

In your specific code example though? No extra references, no abrupt termination—so that In the finally block line will reliably print every time you run it.


内容的提问来源于stack exchange,提问作者skgbanga

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:36:22