pythonreturn-valuefinally

Python: Is it possible to access the return value inside the `finally` clause?


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?

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.


Solution

  • 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.