python try/finally用于流控制

python try/finally用于流控制,python,control-flow,try-catch-finally,Python,Control Flow,Try Catch Finally,我相信这个概念以前就出现过,但我找不到一个好的、简单的答案。使用try/finally处理具有多个返回的函数是否是一种糟糕的方法?比如我有 try: if x: return update(1) else: return update(2) finally: notifyUpdated() 这似乎比将update()命令存储在临时变量中并返回该变量要好 来自: 因此,您可以创建一个类似的函数并使用它我不推荐它。首先,因为即使任一分支中的

我相信这个概念以前就出现过,但我找不到一个好的、简单的答案。使用try/finally处理具有多个返回的函数是否是一种糟糕的方法?比如我有


try:
    if x:
        return update(1)
    else:
        return update(2)
finally:
    notifyUpdated()
这似乎比将update()命令存储在临时变量中并返回该变量要好

来自:


因此,您可以创建一个类似的函数并使用它

我不推荐它。首先,因为即使任一分支中的代码引发异常,也将调用
notifyUpdated()
。您需要这样的东西才能真正实现预期的行为:

try:
    if x:
        return update(1)
    else:
        return update(2)
except:
    raise
else:
    notifyUpdated()
第二,因为
try
块通常表示您正在进行某种异常处理,而您没有,所以您只是为了方便而使用它们。所以这个结构会让人困惑


例如,我认为前两个回答你问题的人(至少其中一人删除了他们的答案)都没有意识到你真正想做什么。混淆代码是不好的,不管它看起来多么方便和聪明。

我想你的意思是你想使用try/finally作为替代:

if x:
    result = update(1)
else:
    result = update(2)
notifyUpdated()
return result

我想这是风格的问题。对于我来说,我喜欢保留
try
来处理异常条件。我不会将其用作流控制语句。

对于不涉及异常的流,我不会使用try/finally。这太狡猾了,不利于自己

这样更好:

if x:
    ret = update(1)
else:
    ret = update(2)
notifyUpdated()
return ret

我认为这是自找麻烦。当您将代码更改为以下内容时,以后会发生什么

try:
    if x:
        return update(1)
    elif y:
        return update(2)
    else:
        return noUpdateHere()
finally:
    notifyUpdated() # even if noUpdateHere()!

充其量,它是大多数代码读者的绊脚石(可能在六个月内甚至是你),因为它使用
try/finally
的目的不同于正常的使用模式。无论如何,它节省的打字量也很小。

我认为在这里,装饰师是个更好的主意

def notifyupdateddecorator(f):
    def inner(*args, **kw):
        retval = f(*args, **kw)
        notifyUpdated()
        return retval
    return inner

@notifyupdateddecorator
def f(x):
    if x:
        return update(1)
    else:
        return update(2)

@notifyupdateddecorator
def g(x):
    return update(1 if x else 2)

没有真正解决OPs问题。
使用
stmt是确保关闭时清理的合法方法虽然我想这是一个风格问题,但我不认为这意味着这个问题没有肯定或否定的答案。我会明确地说“不”,因为你所说的原因和它更令人困惑。我同意。我应该采取更强硬的立场。我错过了那个绊脚石。这种情况在原始版本中已经以隐藏的形式存在,因为如果
update(1)
update(2)
抛出一个异常,这也可能意味着不应该调用
notifyUpdated()
。很好的一点是,前两个答案很容易混淆。嗯,我从来没有见过关于自定义装饰程序的这种情况。您是否有一个链接指向描述此内容的位置?
def notifyupdateddecorator(f):
    def inner(*args, **kw):
        retval = f(*args, **kw)
        notifyUpdated()
        return retval
    return inner

@notifyupdateddecorator
def f(x):
    if x:
        return update(1)
    else:
        return update(2)

@notifyupdateddecorator
def g(x):
    return update(1 if x else 2)