Try-Finally:获取当前返回值

Try-Finally: Get current returning value

我在看 this list of python quirks 并且被这个 returns False:

逗乐了
def t():
    try:
        return True
    finally:
        return False

看到这个我看到了答案here and here,其中给出了原因,那就是finally子句将始终执行,没有例外。

我的问题是,以前的 return 值存储在哪里:

def t():
    try:
        return True
    finally:
        ...

为什么这个 return None 而不是 return 原来的 True

是否可以通过编程方式访问 将被 returned 值?

def t():
    try:
        return True
    finally:
        ...
        # if returning != None: return False

我想知道是否可以在不使用变量的情况下执行此操作,例如:

def t():
    retval = None
    try:
        retval = "Set"
    finally:
        if retval != None:
            return retval
        else:
            return "Not Set"

def t():
    retval = None
    try:
        ...
    finally:
        if retval != None:
            return retval
        else:
            return "Not Set"

return 'Set''Not Set'

Why doesn't this return None but instead returns the original True?

来自docs:

The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement.

所以这意味着如果 return 语句出现在 finally 子句中,该值将被 returned(因为 finally 块保证执行完整地,其中的任何 return 语句也将被执行)。否则,如果 try/except 块要 return 一个值,则该值是 returned.

这意味着

def t():
    try:
        print("Inside try")
        return "Return from try"
    finally:
        print("Inside finally")
        return "Return from finally"

将完全按照以下方式执行:

def t():
    try:
        print("Inside try")
        # start of old finally block, executed "on the way out"
        print("Inside finally")
        return "Return from finally"
        # end of old finally block, inserted right before return statement in try
        return "Return from try"
    finally:
        pass

And is it possible to access the going to be returned value programatically?

不,你不能在代码的其他部分访问 return 语句之后的值而不保存它。