Python:是否可以访问“finally"子句中的返回值? [英] Python: Is it possible to access the return value inside the `finally` clause?

查看:60
本文介绍了Python:是否可以访问“finally"子句中的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 try 子句中有一个 return 语句:

I have a return statement inside a try clause:

def f():
    try:
        return whatever()
    finally:
        pass # How do I get what `whatever()` returned in here?

是否可以在finally 子句中获取返回值?

Is it possible to get the return value inside the finally clause?

这更像是一个理论问题,所以我不是在寻找像将其保存到变量这样的解决方法.

This is more of a theoretical question, so I'm not looking for a workaround like saving it to a variable.

推荐答案

不,它不是 - finally 子句的内容独立于返回机制;如果您确实想查看返回的值,则必须按照您提到的方式进行操作,并将其显式保存在范围内的某个位置.

No, it isn't - the finally clause's content is independent from return mechanics; if you do want to see what value is returned you'd have to do as you mentioned and explicitly save it somewhere that's in-scope.

这篇关于Python:是否可以访问“finally"子句中的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆