Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 277
Ram Rachum Avatar asked Dec 25 '12 21:12

Ram Rachum


People also ask

Will finally work after return python?

A finally block is always run, so the last thing to be returned in the function is whatever is returned in the finally block.

Can we return value from except block in python?

When an exception occurs, both finally and except blocks execute before return . Otherwise only finally executes and else doesn't because the function has already returned. Show activity on this post. The else block isn't executed because you have left the function before it got a chance to do so.

Is it possible to have a return value in an expression?

Since return_42() returns a numeric value, you can use that value in a math expression or any other kind of expression in which the value has a logical or coherent meaning. This is how a caller code can take advantage of a function's return value.

Can we use return in exception in python?

You can avoid unintentionally raising an error using the dictionary's built in get function. Get will return None if the value at the specified key does not exist instead of throwing an exception.


1 Answers

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.

like image 60
Amber Avatar answered Oct 22 '22 07:10

Amber