Skip to main content
 首页 » 编程设计

python之确保一行代码始终执行的最 Pythonic 方法是什么,即使在代码上方执行 return/break 时也是如此

2025年05月04日8itcoder

例如,在下面的代码中,print("Finished computation") 行将不会被执行:

def test(): 
    print("Starting computation...") 
    if True: 
        return 0 
    print("Finished computation")   

保证代码执行的一种方法是使用try/finally:

def test(): 
    try: 
        print("Starting computation...") 
        if True: 
            return 0 
    finally: 
        print("Finished computation") 

感觉有点奇怪,因为在没有使用catch 的情况下使用了try。这被认为是保证执行的最 Pythonic 方式吗?

请您参考如下方法:

这是使用 finally 的替代解决方案 - 一个在程序关闭时执行的关闭函数,依赖于 atexit 模块(退出处理程序)。关闭函数仅在代码正常终止时执行——如果发送终止信号则不会执行。也许其他人可以评论这是否真的是 pythonic 解决方案。

def shutdown(): 
  print("Finished computation") 
 
def test(): 
  print("Starting computation...") 
  if True: 
    return 0 
 
import atexit 
atexit.register(shutdown) 
test()